Python - Pymongo Insert and Update Documents

Dustin picture Dustin · Aug 22, 2013 · Viewed 48.3k times · Source

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)

Answer

Roman Pekar picture Roman Pekar · Aug 22, 2013

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)