Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pymongo find and modify

I have a find query in a mongodb collection and would like this query to also update a field... something like this...

db = pymongo.MongoClient(DB_HOST)[COLLECTION][Product]
new_posts = db.find({'type':{'$ne':'overview'}, 'indice':0, 'thread_id':{'$nin':front_db_ids}, 'updated':{'$exists':False}},{'_id': 0}) + {{'$set': {'updated':'yes'}}, multi=True

I found the findandmodify method but could not find any example of how to use it...

Thanks in advance for any help!

like image 732
user2950162 Avatar asked Apr 29 '14 15:04

user2950162


2 Answers

For those that came here after Googling find_and_modify and discovered it is deprecated (in PyMongo version 3.0, I think), the replacement is find_one_and_update.

Let's say you have a collection called counters and want to increment one of the counters:

db.counters.find_one_and_update({"_id": "counter-id"}, {"$inc":{"sequence_value":1}})

If you want the new document returned, instead of the original pre-updated one, the parameter to pass is new and not, as most documentation states, returnNewDocument:

db.counters.find_one_and_update({"_id": "counter-id"}, {"$inc":{"sequence_value":1}}, new=True)
like image 129
Sid Holland Avatar answered Sep 17 '22 14:09

Sid Holland


Since find_and_modify is deprecated use find_one_and_update method instead, use return_document parameter of find_one_and_update method to return either updated document or unupdated document.

update_object = collection_object.find_one_and_update({'_id': ObjectId(pk)}, {'$set': data}, return_document=ReturnDocument.AFTER)

Here, return_document is set as ReturnDocument.AFTER, which will return a document after it's updated. If it's set as BEFORE, it'll return the document before it was updated.

like image 40
Yogesh Kate Avatar answered Sep 17 '22 14:09

Yogesh Kate