CRUD Operations with PyMongo:
CRUD (Create, Read, Update, Delete) operations are fundamental when working with databases. PyMongo, the official MongoDB driver for Python, provides methods to perform these operations seamlessly.
- Creating Documents: Creating documents involves inserting new data into a collection. PyMongo's
insert_one()
andinsert_many()
methods accomplish this.
# Insert a single document
new_doc = {"name": "Ajit", "age": 28}
collection.insert_one(new_doc)
# Insert multiple documents
new_docs = [
{"name": "Bob", "age": 32},
{"name": "Charlie", "age": 25}
]
collection.insert_many(new_docs)
- Reading Documents: Reading documents involves querying the database to retrieve data. PyMongo's
find()
method and other query methods allow you to retrieve data based on specific criteria.
# Find all documents
all_docs = collection.find()
# Find documents that match a specific condition
young_people = collection.find({"age": {"$lt": 30}})
- Updating Documents: Updating documents allows you to modify existing data. PyMongo's
update_one()
andupdate_many()
methods help you achieve this.
# Update a single document
collection.update_one({"name": "Ajit"}, {"$set": {"age": 28}})
# Update multiple documents
collection.update_many({"age": {"$lt": 30}}, {"$inc": {"age": 1}})
- Deleting Documents: Deleting documents involves removing data from a collection. PyMongo's
delete_one()
anddelete_many()
methods enable you to delete documents based on specified criteria.
# Delete a single document
collection.delete_one({"name": "Alice"})
# Delete multiple documents
collection.delete_many({"age": {"$gt": 30}})
Top comments (0)