class News(Document):
news_id = IntField()
post_date = DatetimeField()
last_modified = DatetimeField()
这是文档
我想在 last_modified 大于 post_date 的地方进行 mongoengine 查询
有点像
News.objects(last_modified__gte = post_date) #mongoengine 查询
有什么方法可以进行这种类型的查询吗?
请您参考如下方法:
在 django 中,您可以使用 F 执行此操作,但由于 F 不适用于 mongoengine,因此请使用 where 方法-
query = "this.{last_modified}>this.{post_date}"
db_fields = {
'last_modified': News._fields['last_modified'],
'post_date': News._fields['post_date']
}
results = News.objects.where(query.format(*db_fields))
根据 mongoengine 文档,'$where' 子句被自动替换
def where(self, where_clause):
"""Filter ``QuerySet`` results with a ``$where`` clause (a Javascript
expression). Performs automatic field name substitution like
:meth:`mongoengine.queryset.Queryset.exec_js`.
.. note:: When using this mode of query, the database will call your
function, or evaluate your predicate clause, for each object
in the collection.
.. versionadded:: 0.5
"""
或
您可以直接查询 mongodb -
query = "this.{last_modified}>this.{post_date}"
db_fields = {
'last_modified': News._fields['last_modified'],
'post_date': News._fields['post_date']
}
collection = News._get_collection()
results = list(collection.find({"$where": query.format(*db_fields)}))
注意:- 您不应在 mongo 查询中硬编码 db_fields 名称。
