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

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS Security LIVE!

Hosted by security experts, AWS Security LIVE! showcases AWS Partners tackling real-world security challenges. Join live and get your security questions answered.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️