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!
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)
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.
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