In MongoDB, To update a row (document) in MongoDB using Python, we typically use the "update_one()" or "update_many()" method provided by the `pymongo` library.
Here's an example of how you can update a row in MongoDB using "PyMongo":
# Define the update operation update = {"$set": {"field_to_update": "new_value"}}
After importing "pymongo", we must provide a connection URL and database name to MongoClient.
# import pymongo library import pymongo # Connect to MongoDB client = pymongo.MongoClient("mongodb://localhost:27017/") db = client["your_database_name"] collection = db["your_collection_name"]
Make sure to replace "your_database_name" and "your_collection_name" with your actual database, and collection name respectively.
# Define the filter to find the document to update filter = {"_id": ObjectId("document_id_to_update")} # Update a single document that matches the filter result = collection.update_one(filter, update) # Print information about the update # It will display no. of Document matched above query. print("Matched:", result.matched_count) # it will display actual no. of Document updated/affected. print("Modified:", result.modified_count)
"filter" specifies the criteria for finding the document we want to update. Replace "document_id_to_update" with the actual "ID" of the document we want to update.
"update" specifies the modification we want to make. In this case, we use "$set" to update specific fields.
"update_one()" is used to update a single document that matches the filter. If we want to update multiple documents, we can use "update_many()" instead.
"result.matched_count" returns the number of documents that matched the filter, and "result.modified_count" returns the number of documents that were modified.
Make sure to replace "document_id_to_update", and "field_to_update" with your actual database, and collection name respectively.
Using the "filter" object, we can find all documents that matched the criteria and were eligible for the update.
With the help of "$set: { any_key_data_to_be_update }" we can modify our existing documents in the collection.
# Define the filter to find the documents to update filter = {age: {$gt: 18}} # will update all document whose age is greater than 18 # Define the update operation update = {"$set": {"isEligible": true}} # Update a single document that matches the filter result = collection.update_many(filter, update) # Print information about the update # It will display no. of Documents matched above query. print("Matched:", result.matched_count) # it will display actual no. of Document updated/affected. print("Modified:", result.modified_count)
Note: "update_many()" updates all documents that match the filter with the specified update.