Using PyMongo, I have a set of dict's in a list that I'd like to submit to my MongoDB. Some of the items in the list are new entries, and some are to update.
Example:
On Server Database:
[{"_id" : 1, "foo" : "bar}]
To send to database:
[{"_id" : 1, "foo" : "HELLO"}, {"_id" : 2, "Blah" : "Bloh"}]
I'm currently using the following to insert documents, but how would I do something like stated above? Any help is appreciated!
collection.insert(myDict)
Updating all Documents in a Collection. PyMongo includes an update_many() function which updates all the documents which satisfy the given query. filter – It is the first parameter which is a criteria according to which the documents that satisfy the query are updated.
You can update a record, or document as it is called in MongoDB, by using the update_one() method. The first parameter of the update_one() method is a query object defining which document to update. Note: If the query finds more than one record, only the first occurrence is updated.
Use upsert
option:
from pymongo import MongoClient
cl = MongoClient()
coll = cl["local"]["test2"]
data = [{"_id" : 1, "foo" : "HELLO"}, {"_id" : 2, "Blah" : "Bloh"}]
for d in data:
coll.update({'_id':d['_id']}, d, True)
You can also use save
import pymongo
con = pymongo.MongoClient()
coll = con.db_name.collection_name
docs = [{"_id" : 1, "foo" : "HELLO"}, {"_id" : 2, "Blah" : "Bloh"}]
for doc in docs:
coll.save(doc)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With