use*_*162 4 python mongodb pymongo
我在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
Run Code Online (Sandbox Code Playgroud)
我找到了findandmodify方法,但找不到任何如何使用它的例子......
在此先感谢您的帮助!
nam*_*mit 13
例如,参考文档
db.update({"_id": acs_num}, {"$set": mydata}, upsert = True)
Run Code Online (Sandbox Code Playgroud)
或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 {}
例如:
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!'}]
Run Code Online (Sandbox Code Playgroud)
Sid*_*and 13
对于那些在谷歌搜索后find_and_modify发现它已被弃用的人(我认为在 PyMongo 3.0 版中),替换为find_one_and_update.
假设您有一个名为的集合counters并希望增加其中一个计数器:
db.counters.find_one_and_update({"_id": "counter-id"}, {"$inc":{"sequence_value":1}})
Run Code Online (Sandbox Code Playgroud)
如果您希望返回新文档,而不是原始的预更新文档,则传递的参数是new而不是,正如大多数文档所述returnNewDocument:
db.counters.find_one_and_update({"_id": "counter-id"}, {"$inc":{"sequence_value":1}}, new=True)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27574 次 |
| 最近记录: |