PYTHON Tutorial

CRUD Operations in MongoDB

Key Concepts:

  • Create (insert): Adds a new document to a collection.
  • Read (query): Retrieves documents from a collection based on specified criteria.
  • Update: Modifies existing documents in a collection.
  • Delete: Removes documents from a collection.

Steps for Performing CRUD Operations:

Inserting Documents:
  • Use the insert_one() method for inserting a single document.
  • Use the insert_many() method for inserting multiple documents.
Querying Documents:
  • Use the find() method to retrieve documents based on specified filters.
  • Filter documents using query operators (e.g., $eq, $gt, $lt).
Updating Documents:
  • Use the update_one() method to update a single document.
  • Use the update_many() method to update multiple documents.
  • Use update operators (e.g., $set, $inc, $unset) to modify fields.
Deleting Documents:
  • Use the delete_one() method to delete a single document.
  • Use the delete_many() method to delete multiple documents.
  • Specify deletion criteria using query filters.

Python Example:

import pymongo

# Establish a connection to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017")

# Get the database and collection
db = client.my_database
collection = db.my_collection

# Create a document
new_doc = {"name": "John Doe", "age": 30}
result = collection.insert_one(new_doc)
print(f"Inserted document with id: {result.inserted_id}")

# Query for documents
results = collection.find({"name": "John Doe"})
for doc in results:
    print(doc)

# Update a document
result = collection.update_one({"name": "John Doe"}, {"$set": {"age": 31}})
print(f"Updated {result.modified_count} document(s)")

# Delete a document
result = collection.delete_one({"name": "John Doe"})
print(f"Deleted {result.deleted_count} document(s)")

Tips for Accessibility and Ease of Use:

  • Use descriptive variable and function names.
  • Follow consistent naming conventions.
  • Provide documentation or comments to explain the code.
  • Avoid using complex or nested expressions.
  • Break down large functions into smaller, manageable chunks.