Python Pymongo 查找和修改

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23368575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:50:49  来源:igfitidea点击:

Pymongo find and modify

pythonmongodbpymongo

提问by user2950162

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

我在 mongodb 集合中有一个查找查询,并且希望这个查询也更新一个字段......像这样......

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

我找到了 findandmodify 方法,但找不到如何使用它的任何示例...

Thanks in advance for any help!

在此先感谢您的帮助!

采纳答案by namit

refer the documentation, for example

参考文档,例如

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

or find_and_modifyaccording to docssays Returns 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 {}

find_and_modify根据文档Returns 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 {}


for example:


例如:

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!'}]

回答by Sid Holland

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

对于那些在谷歌搜索后find_and_modify发现它已被弃用的人(我认为在 PyMongo 3.0 版中),替换为find_one_and_update.

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

假设您有一个名为的集合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 newand not, as most documentation states, returnNewDocument:

如果您希望返回新文档,而不是原始的预更新文档,则传递的参数是new而不是,正如大多数文档所述returnNewDocument

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