这里我有内部test.test
收集两个文件:Pymongo - 古怪的聚集行为
> db.test.find()
{ "_id" : ObjectId("AAA"), "last_updated" : 1000, "update_interval" : 50 }
{ "_id" : ObjectId("BBB"), "last_updated" : 1200, "update_interval" : 50 }
我想找到应该(通过测试last_updated <= now - update_interval
表达)更新文件。
首先,我试图用Python pymongo如下:
from pymongo import MongoClient
db = MongoClient().test
now = 1225
r = db.test.find({
'last_updated': {'$lte': {'$subtract': [now, '$update_interval']}}
})
for item in r:
print(r)
但是,它不显示任何信息。但是当我将{'$subtract': [now, '$update_interval']}
更改为硬编码值1175
时,它工作正常。
我认为我不能使用$subtract
外聚集的管道,所以我尝试另:
r = db.test.aggregate([
{
'$match': {
'last_updated': {'$lte': {'$subtract': [now, '$update_interval']}},
},
},
])
嗯,它只是看起来与以前的一个,并且是它没有工作过。
最后,我给了最后一次尝试:
r = db.test.aggregate([
{
'$project': {
'when_to_update': {'$subtract': [now, '$update_interval']},
'last_updated': True,
'update_interval': True,
},
},
{
'$match': {
'last_updated': {'$lte': '$when_to_update'},
},
},
])
好吧,它不会再工作。但奇怪的是,当我刚刚获得通过的$project
管道,结果是这样的:
{'_id': ObjectId('AAA'), 'last_updated': 1000.0, 'update_interval': 50.0, 'when_to_update': 1175.0}
{'_id': ObjectId('BBB'), 'last_updated': 1200.0, 'update_interval': 50.0, 'when_to_update': 1175.0}
所以应该通过$match
管道太后工作!我错过了什么吗?等待你的答案,谢谢。
你不能比较比赛阶段的领域。这是可能的3.6版本。简单的解决方法是改变''can_update':{'$ lte':['$ last_updated', {'$ subtract':[now,'$ update_interval']}]}''和'{''''匹配':{ 'can_update':true, }, }' – Veeram
[MongoDb查询条件比较2个字段]的可能重复(https://stackoverflow.com/questions/4442453/mongodb-query-condition-on-比较2字段) – Veeram