20

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)

4 Answers 4

30

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)
Sign up to request clarification or add additional context in comments.

5 Comments

Is there any way to do this with a single API call ? Something like a "bulk" update, for better perfomances.
@John Did you figure out a way to do this in bulk? something similar to insert_many
How could I obtain the object_id of each inserted object? @Roman Pekar
DeprecationWarning: update is deprecated. Use replace_one, update_one or update_many instead. [Pymongo 3.12.0]
8

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)

1 Comment

From Docs: DEPRECATED - Use insert_one() or replace_one() instead.
8

You have to use the upsert to update (or insert) your data

from pymongo import MongoClient
client = MongoClient()
collection = client.my_database.my_collection

objects = [{"_id" : 1, "foo" : "HELLO"}, {"_id" : 2, "Blah" : "Bloh"}]
for obj in objects:
     collection.replace_one({"_id": obj["_id"]}, obj, upsert=True) 

Use replace_one as the update method is deprecated:

https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.replace_one

If you want to use bulk update:

from pymongo import ReplaceOne

update_objects = list()
for obj in objects:
    update_objects.append(ReplaceOne( {'_id': obj['_id']},  obj, upsert=True))

collection.bulk_write(update_objects)

Comments

5

For pymongo 3.0 and later:

import pymongo
con = pymongo.MongoClient()
collection = con.db_name.collection_name

docs = [{"_id" : 1, "foo" : "HELLO"}, {"_id" : 2, "Blah" : "Bloh"}]
for d in docs:
    collection.update_many({'_id':d['_id']}, d,True)

Ref: http://api.mongodb.org/python/current/api/pymongo/collection.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.