PYTHON Tutorial
insert_one()
method for inserting a single document.insert_many()
method for inserting multiple documents.find()
method to retrieve documents based on specified filters.$eq
, $gt
, $lt
).update_one()
method to update a single document.update_many()
method to update multiple documents.$set
, $inc
, $unset
) to modify fields.delete_one()
method to delete a single document.delete_many()
method to delete multiple documents.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)")