Python MongoDB Insert Document
In MongoDB, you can insert documents (which are similar to rows in a relational database) into collections. MongoDB documents are stored in JSON-like format called BSON (Binary JSON), but you can work with Python dictionaries to insert documents using the pymongo library.
Steps to Insert a Document into MongoDB Using Python
- Install PyMongo (if not already installed):
pip install pymongo - Connect to MongoDB, access the database, and insert documents into a collection.
Example: Inserting a Single Document
You can insert a single document using the insert_one() method.
import pymongo
# Step 1: Connect to MongoDB (adjust the URL as needed)
client = pymongo.MongoClient("mongodb://localhost:27017/")
# Step 2: Access or create a database
mydb = client["mydatabase"]
# Step 3: Access or create a collection
mycol = mydb["customers"]
# Step 4: Create a document (Python dictionary)
mydict = { "name": "John", "address": "123 Elm Street" }
# Step 5: Insert the document into the collection
x = mycol.insert_one(mydict)
# Step 6: Print the inserted document ID
print("Inserted document ID:", x.inserted_id)
Explanation:
- Connect to MongoDB: We connect to the MongoDB instance on
localhost(change the URL if connecting to a remote server). - Access or Create Database: The line
client["mydatabase"]accesses themydatabasedatabase (creates it if it doesn’t exist yet). - Access or Create Collection:
mycol = mydb["customers"]accesses thecustomerscollection, which is created if it doesn’t exist. - Insert a Document: Using
insert_one(), we insert the document (represented as a Python dictionary) into thecustomerscollection.
Example: Inserting Multiple Documents
You can insert multiple documents at once using the insert_many() method.
import pymongo
# Step 1: Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
# Step 2: Access or create a database
mydb = client["mydatabase"]
# Step 3: Access or create a collection
mycol = mydb["customers"]
# Step 4: Create multiple documents (list of Python dictionaries)
mylist = [
{ "name": "Amy", "address": "456 Oak Street" },
{ "name": "Mark", "address": "789 Maple Avenue" },
{ "name": "Sara", "address": "101 Pine Road" }
]
# Step 5: Insert multiple documents into the collection
x = mycol.insert_many(mylist)
# Step 6: Print the inserted document IDs
print("Inserted document IDs:", x.inserted_ids)
Explanation:
- We create a list of dictionaries, where each dictionary represents a document to be inserted.
insert_many()is used to insert multiple documents into the collection.- The
inserted_idsattribute returns a list of IDs for the inserted documents.
Inserting a Document with an Explicit _id
MongoDB automatically creates a unique _id field for each document. However, you can explicitly set the _id if needed:
mydict = { "_id": 1, "name": "John", "address": "123 Elm Street" }
x = mycol.insert_one(mydict)
If you try to insert a document with a duplicate _id, it will raise an error.
Handling Errors
When inserting data, you might want to handle potential errors, such as trying to insert a document with a duplicate _id:
from pymongo.errors import DuplicateKeyError
mydict = { "_id": 1, "name": "John", "address": "123 Elm Street" }
try:
x = mycol.insert_one(mydict)
print("Inserted document ID:", x.inserted_id)
except DuplicateKeyError:
print("Document with that _id already exists.")
Example: Full Flow (Connecting, Inserting, and Retrieving Data)
import pymongo
# Step 1: Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
# Step 2: Access or create a database
mydb = client["mydatabase"]
# Step 3: Access or create a collection
mycol = mydb["customers"]
# Step 4: Insert a document
mydict = { "name": "John", "address": "123 Elm Street" }
mycol.insert_one(mydict)
# Step 5: Insert multiple documents
mylist = [
{ "name": "Amy", "address": "456 Oak Street" },
{ "name": "Mark", "address": "789 Maple Avenue" },
{ "name": "Sara", "address": "101 Pine Road" }
]
mycol.insert_many(mylist)
# Step 6: Retrieve all documents in the collection
for doc in mycol.find():
print(doc)
This example inserts both a single document and multiple documents into the customers collection, then retrieves all documents from the collection using the find() method.
Summary:
insert_one(): Use this method to insert a single document into a collection.insert_many(): Use this method to insert multiple documents at once.- MongoDB automatically creates an
_idfield for each document unless you provide one explicitly. - Handle potential errors, such as duplicate
_idinsertions, using appropriate error handling (DuplicateKeyError).