DEV Community

Cover image for CRUD Operations with PyMongo:
ajitdhulam for Python Discipline @EPAM India

Posted on

CRUD Operations with PyMongo:

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() and insert_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)
Enter fullscreen mode Exit fullscreen mode
  • 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}})
Enter fullscreen mode Exit fullscreen mode
  • Updating Documents: Updating documents allows you to modify existing data. PyMongo's update_one() and update_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}})
Enter fullscreen mode Exit fullscreen mode
  • Deleting Documents: Deleting documents involves removing data from a collection. PyMongo's delete_one() and delete_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}})
Enter fullscreen mode Exit fullscreen mode

Top comments (0)