python - 如何在 PyMongo 中为更新方法定义非常具体的过滤器

标签 python mongodb pymongo

我的项目中有一个非常具体的查询,它返回日期最低的文档:

   data = collection.find({'status': 'to_be_posted'}).sort('creation_date', pymongo.ASCENDING).limit(1)[0]

但现在我在更新与此查询匹配的文档时遇到问题。类似的东西根本行不通:

collection.update( { 'status' : 'to_be_posted' },
           { '$set' : {
               'status' : 'posted'
           },
           { array_filters: [{ $group : { _id: null, max: { $max : "$creation_date" }}}]
           } } )

...或者类似的东西:

collection.update( {'status': 'to_be_posted'}.sort('creation_date', pymongo.ASCENDING).limit(1),
           { '$set' : {
               'status' : 'posted'
           } } )

我需要将具有最低日期和“to_be_posted”状态的文档更新为“已发布”状态。 我不知道如何为这种更新方法编写正确的查询过滤器。我应该使用哪些运算符?我可以使用查询修饰符吗?

最佳答案

pymongo.collection.Collection.find_one_and_update可用于执行查找和更新查询。

Parameters

filter: A query that matches the document to update.

update: The update operations to apply.

projection (optional): A list of field names that should be returned in the result document or a mapping specifying the fields to include or exclude. If projection is a list "_id" will always be returned. Use a dict to exclude fields from the result (e.g. projection={'_id': False}).

sort (optional): a list of (key, direction) pairs specifying the sort order for the query. If multiple documents match the query, they are sorted and the first is updated.

upsert (optional): When True, inserts a new document if no document matches the query. Defaults to False.

return_document: If :attr:ReturnDocument.BEFORE (the default), returns the original document before it was updated, or None if no document matches. If :attr:ReturnDocument.AFTER, returns the updated or inserted document.

array_filters (optional): A list of filters specifying which array elements an update should apply. Requires MongoDB 3.6+.

session (optional): a :class:~pymongo.client_session.ClientSession.

**kwargs (optional): additional command arguments can be passed as keyword arguments (for example maxTimeMS can be used with recent server versions).

import pymongo
from pymongo.collection import ReturnDocument

filter = {'status': 'to_be_posted'}
update = {'$set': {'status' : 'posted'}}
sort = [('creation_date', pymongo.ASCENDING)]
updated_doc = collection.find_one_and_update(
                  filter, update, sort=sort, 
                  return_document=ReturnDocument.AFTER
              )

关于python - 如何在 PyMongo 中为更新方法定义非常具体的过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52265687/

相关文章:

node.js - 如何同步向mongo插入数据(Nodejs、Express)

python - django Wagtail 嵌入视频未显示

python - 在 barh 中显示数据帧的值

python - 无法获得单例\在 python

python - Pymongo - 如何将文档插入到集合的前面?

python - pymongo.errors.ServerSelectionTimeoutError : localhost:27017: [Errno 61] Connection refused

python - 大数据库中的 MongoDB 计数非常慢

python - 图像处理:道路提取

angularjs - 在 Mongoose 中分组嵌套内部数组

java - MongoDB如何使用morphia加载引用文档的两个属性