Mongodb Insert in Python
To insert data into a MongoDB collection using Python, you use the insert_one() method to insert a single document, or the insert_many() method to insert multiple documents at once.
Here’s a guide on how to insert documents into a MongoDB collection using Python:
1. Install pymongo
Before you can use MongoDB with Python, make sure to install the pymongo library:
pip install pymongo2. Connect to MongoDB
Make sure you have MongoDB running on your machine or use a cloud-hosted version like MongoDB Atlas.
To connect to your MongoDB instance:
import pymongo# Connect to MongoDB (localhost by default)client = pymongo.MongoClient("mongodb://localhost:27017/")# Access the databasedb = client["mydatabase"]# Access the collectioncollection = db["mycollection"]This code connects to a MongoDB instance running on the default localhost:27017 port and accesses the mydatabase database and the mycollection collection.
3. Insert a Single Document Using insert_one()
To insert a single document, you can use the insert_one() method.
# Define the document (record) you want to insertdocument = { "name": "Alice", "age": 25, "city": "New York"}# Insert the document into the collectionresult = collection.insert_one(document)# Print the inserted document's unique IDprint(f"Document inserted with ID: {result.inserted_id}")In this example:
The
insert_one()method inserts a single document into the collection.result.inserted_idgives you the ID of the newly inserted document.
4. Insert Multiple Documents Using insert_many()
To insert multiple documents, use the insert_many() method.
# Define multiple documents to insertdocuments = [ {"name": "Bob", "age": 30, "city": "San Francisco"}, {"name": "Charlie", "age": 35, "city": "Chicago"}, {"name": "David", "age": 40, "city": "Los Angeles"}]# Insert the documents into the collectionresult = collection.insert_many(documents)# Print the IDs of the inserted documentsprint(f"Documents inserted with IDs: {result.inserted_ids}")In this example:
The
insert_many()method inserts a list of documents into the collection.result.inserted_idsgives you a list of IDs of the newly inserted documents.
5. Handling Insert Errors
MongoDB allows you to insert documents even if some fields are missing or if there are duplicate values for non-unique fields. However, it’s good practice to handle potential errors when inserting data. For instance, you can use try-except to catch and handle any exceptions.
try: # Define a document to insert document = {"name": "Eve", "age": 28, "city": "Miami"} # Insert the document into the collection result = collection.insert_one(document) print(f"Document inserted with ID: {result.inserted_id}")except pymongo.errors.PyMongoError as e: print(f"Error inserting document: {e}")6. Verify Insertion
To verify if the documents were inserted successfully, you can query the collection.
# Find all documents in the collectionfor doc in collection.find(): print(doc)7. Close the Connection
Once you are done with the operations, make sure to close the connection:
client.close()Conclusion
insert_one(): Used to insert a single document into a collection.insert_many(): Used to insert multiple documents into a collection.Error Handling: Use try-except blocks to catch potential MongoDB errors.
Verification: You can verify the insertion by querying the collection.
This should help you get started with inserting data into MongoDB using Python.