我的项目中有一个非常具体的查询,它返回日期最低的文档:
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. Ifprojection
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): WhenTrue
, inserts a new document if no document matches the query. Defaults toFalse
.
return_document
: If :attr:ReturnDocument.BEFORE
(the default), returns the original document before it was updated, orNone
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/