Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Pymongo Insert and Update Documents

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)
like image 221
Dustin Avatar asked Aug 22 '13 03:08

Dustin


People also ask

How do I update all documents in Pymongo?

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.

How do you update a record in Pymongo?

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.


2 Answers

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)
like image 67
Roman Pekar Avatar answered Oct 08 '22 03:10

Roman Pekar


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)
like image 22
lovesh Avatar answered Oct 08 '22 04:10

lovesh