Introduction
Inserting documents into a MongoDB collection is a fundamental task when working with this NoSQL database. MongoDB stores data in JSON-like documents, making it highly flexible and easy to work with. Python, with its extensive library support, makes it easy to interact with MongoDB. In this guide, we will use the pymongo
library to insert documents into a MongoDB collection.
Setting Up
Install PyMongo
First, you need to install the PyMongo library. You can install it using pip:
pip install pymongo
Connecting to MongoDB
To insert documents into a MongoDB collection, you need to connect to the MongoDB server. The default hostname is localhost
, and the default port is 27017
.
Example: Connecting to MongoDB
from pymongo import MongoClient
# Connect to the MongoDB server
client = MongoClient('localhost', 27017)
# Verify connection
print("Connected to MongoDB server")
Creating a Database and Collection
Before inserting documents, you need to specify the database and collection where the documents will be stored.
Example: Creating a Database and Collection
# Access a database
db = client['mydatabase']
# Access a collection
collection = db['employees']
print("Database and collection ready")
Inserting Documents
You can insert documents into a collection using the insert_one()
and insert_many()
methods.
Example: Inserting a Single Document
# Insert a single document
employee = {
"name": "John Doe",
"age": 28,
"position": "Software Engineer"
}
result = collection.insert_one(employee)
print("Document inserted with ID:", result.inserted_id)
Example: Inserting Multiple Documents
# Insert multiple documents
employees = [
{"name": "Jane Smith", "age": 32, "position": "Project Manager"},
{"name": "Mike Johnson", "age": 45, "position": "CTO"},
{"name": "Emma Davis", "age": 29, "position": "Data Scientist"}
]
result = collection.insert_many(employees)
print("Multiple documents inserted with IDs:", result.inserted_ids)
Verifying the Insertion
After inserting documents, you can verify the insertion by querying the collection.
Example: Querying the Collection
# Query the collection
documents = collection.find()
for doc in documents:
print(doc)
Handling Exceptions
It’s important to handle exceptions that might occur during the database operations to ensure that your program can handle errors gracefully.
Example: Handling Exceptions
from pymongo.errors import PyMongoError
try:
# Insert a single document
employee = {
"name": "John Doe",
"age": 28,
"position": "Software Engineer"
}
result = collection.insert_one(employee)
print("Document inserted with ID:", result.inserted_id)
except PyMongoError as e:
print("An error occurred:", e)
Complete Example
Here is a complete example that includes connecting to MongoDB, creating a collection, inserting documents, and verifying the insertion.
from pymongo import MongoClient
from pymongo.errors import PyMongoError
# Connect to the MongoDB server
client = MongoClient('localhost', 27017)
# Access a database
db = client['mydatabase']
# Access a collection
collection = db['employees']
try:
# Insert a single document
employee = {
"name": "John Doe",
"age": 28,
"position": "Software Engineer"
}
result = collection.insert_one(employee)
print("Document inserted with ID:", result.inserted_id)
except PyMongoError as e:
print("An error occurred:", e)
# Insert multiple documents
employees = [
{"name": "Jane Smith", "age": 32, "position": "Project Manager"},
{"name": "Mike Johnson", "age": 45, "position": "CTO"},
{"name": "Emma Davis", "age": 29, "position": "Data Scientist"}
]
try:
result = collection.insert_many(employees)
print("Multiple documents inserted with IDs:", result.inserted_ids)
except PyMongoError as e:
print("An error occurred:", e)
# Verify the insertion
documents = collection.find()
print("Documents in collection:")
for doc in documents:
print(doc)
Conclusion
Inserting documents into a MongoDB collection using Python is straightforward with the pymongo
library. By following the steps outlined above, you can easily connect to a MongoDB server, create collections, insert single and multiple documents, and verify the insertion. This provides a solid foundation for managing and analyzing your data programmatically using Python.