Mongoengine查询将一个字段与另一个字段进行比较

时间:2015-09-24 11:29:53

标签: python mongodb flask mongodb-query mongoengine

class News(Document):
    news_id = IntField()
    post_date = DatetimeField()
    last_modified = DatetimeField()

这是文件

我想进行mongoengine查询,其中last_modified大于post_date

这样的东西

News.objects(last_modified__gte = post_date)#mongoengine query

有没有办法进行此类查询?

1 个答案:

答案 0 :(得分:-1)

在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名称进行硬编码。