Here I have two documents inside test.test
collection:
> db.test.find()
{ "_id" : ObjectId("AAA"), "last_updated" : 1000, "update_interval" : 50 }
{ "_id" : ObjectId("BBB"), "last_updated" : 1200, "update_interval" : 50 }
I want to find documents that should be updated(by testing last_updated <= now - update_interval
expression).
First, I tried following in Python with 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)
However, it doesn't print anything. But when I change {'$subtract': [now, '$update_interval']}
to hardcoded value 1175
, it works properly.
I thought that I can't use $subtract
outside of aggregation pipelines, so I tried another:
r = db.test.aggregate([
{
'$match': {
'last_updated': {'$lte': {'$subtract': [now, '$update_interval']}},
},
},
])
Um, it just looks identical to previous one, and yes it didn't work too.
Finally, I gave last try:
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'},
},
},
])
Ok, it doesn't work again. But the weird thing is, when I passed just $project
pipeline, the result looks like:
{'_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}
So it should work after passing $match
pipeline too! Am I missing something? Waiting for your answers, thanks.