如何检索两个字段值与 pymongo 相等的所有文档?

How to retrieve all documents where two fields' value are equals with pymongo?

我有一个 MongoDB 集合,我想使用 python.

提取某些日期字段小于其他日期字段的所有文档

我在robomongo知道怎么做:

db.getCollection('myCollection').find({'date1' : {'$lt' : ISODate(this.date2)}})

但是当我使用 pymongo 时这不起作用。我尝试使用 datetime 而不是 ISODate 但没有成功。

编辑:date1 和 date2 都是字段名称

有什么解决办法吗?

API pages开始,您可以使用

d = datetime.datetime(2009, 11, 12, 12)
collection.find({"date": {"$lt": d}})

您需要使用 .aggregate() method which provides access to the aggregation pipeline and the $redact 运算符。

pipeline = [
    {'$match': {'date1': {'$exists': True}, 'date2': {'$exists': True}}},
    {'$redact': {'$cond': [{'$lt': ['$date1', '$date2']}, '$$KEEP', '$$PRUNE']}}
]
collection.aggregate(pipeline)

$redact 将 return 所有文档使用 $$KEEP and discards those that don't match using the $$PRUNE 变量匹配条件。

$match 阶段是可选的,但很好。它所做的只是初步过滤,限制了将在下一阶段处理的文档数量。 $redact 也会进行集合扫描,因此 $match 只会让事情变得更好。