Pymongo find and change

I have a search request in the mongodb collection and would like this request to also update the 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 your help!

+4
source share
2 answers

refer to the documentation for example

db.update({"_id": acs_num}, {"$set": mydata}, upsert = True)

or find_and_modifyaccording to docs saysReturns either the object before or after modification based on new parameter. If no objects match the query and upsert is false, returns None. If upserting and new is false, returns {}


eg:

In [1]: from pymongo import MongoClient

In [2]: client = MongoClient("mongodb://localhost:27017")
   ...: db = client["testdb"]
   ...: mycollection = db["mydb"]
   ...: 

In [3]: import datetime
   ...: post1 = {"author": "Mike", "text": "My first blog post!", "tags": ["mongodb", "python", "pymongo"], "date": datetime.datetime.utcnow()}
   ...: 

In [4]: mycollection.insert(post1)
Out[4]: ObjectId('535fd580c314f91d28c35ee1')

In [5]: [x for x in mycollection.find()]
Out[5]: 
[{u'_id': ObjectId('535fd580c314f91d28c35ee1'),
  u'author': u'Mike',
  u'date': datetime.datetime(2014, 4, 29, 16, 38, 15, 457000),
  u'tags': [u'mongodb', u'python', u'pymongo'],
  u'text': u'My first blog post!'}]

In [6]: mycollection.find_and_modify(query={'author':'Mike'}, update={"$set": {'author': "Mike2"}}, upsert=False, full_response= True)
Out[6]: 
{u'lastErrorObject': {u'n': 1, u'updatedExisting': True},
 u'ok': 1.0,
 u'value': {u'_id': ObjectId('535fd580c314f91d28c35ee1'),
  u'author': u'Mike',
  u'date': datetime.datetime(2014, 4, 29, 16, 38, 15, 457000),
  u'tags': [u'mongodb', u'python', u'pymongo'],
  u'text': u'My first blog post!'}}

In [7]: [ x for x in mycollection.find()]
Out[7]: 
[{u'_id': ObjectId('535fd580c314f91d28c35ee1'),
  u'author': u'Mike2',
  u'date': datetime.datetime(2014, 4, 29, 16, 38, 15, 457000),
  u'tags': [u'mongodb', u'python', u'pymongo'],
  u'text': u'My first blog post!'}]
+11
source

For those who came here after Googling find_and_modifyand found that it is out of date (in PyMongo version 3.0, I think), the replacement is find_one_and_update.

, counters :

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

, , , new , , returnNewDocument:

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

Source: https://habr.com/ru/post/1538606/


All Articles