请看这个文件:
{
"creation_date" : ISODate("2015-02-10T03:00:00.000Z"),
"days_of_validity": 10
}
我正在尝试查询所有文件
"creation_date" < today - "days_of_validity"
这是我迄今为止的最大努力:
docs.find({"creation_date":
{$lt: new Date().setDate(new Date().getDate() - days_of_validity)}})
事情是,显然我不能将js函数与mongo字段混合。
关于如何解决这个问题的任何想法?
答案 0 :(得分:0)
您还有另一个问题,即您尝试将一个字段与另一个字段进行比较:days_of_validity
实际上并不是一个有效变量。您需要进行聚合。像这样:
db.post.aggregate([
{"$project":{
"creation_date":1,
"earliest":{"$subtract":
[ISODate(), {"$multiply":["$days_of_validity", 1000*3600*24]}]}}},
{"$project": {"delta": {"$subtract":["$creation_date", "$earliest"]}}},
{"$match":{"delta": {"$lt": 0}}}])
答案 1 :(得分:0)
您好我尝试了更多的计算希望,这将有助于您
db.collectionName.aggregate({
"$project": {
"crationTimestamp": {
"$subtract": [{
"$divide": [{
"$subtract": ["$creation_date", new Date("1970-01-01")]
}, 1]
}, {
"$mod": [{
"$divide": [{
"$subtract": ["$creation_date", new Date("1970-01-01")]
}, 1]
}, 1]
}]
},
"days_of_validity": "$days_of_validity",
"todayTimeStamp": {
"$subtract": [new Date().getTime(), 0]
},
"creation_date": "$creation_date"
}
}, {
"$project": {
"dayDiff": {
"$multiply": ["$days_of_validity", 24, 60, 60, 1000]
},
"todayTimeStamp": "$todayTimeStamp",
"crationTimestamp": "$crationTimestamp",
"days_of_validity": "$days_of_validity",
"creation_date": "$creation_date"
}
}, {
"$project": {
"todayAndDaysDiff": {
"$subtract": ["$todayTimeStamp", "$dayDiff"]
},
"crationTimestamp": "$crationTimestamp",
"days_of_validity": "$days_of_validity",
"creation_date": "$creation_date"
}
}, {
"$project": {
"finalDiff": {
"$subtract": ["$crationTimestamp", "$todayAndDaysDiff"]
},
"days_of_validity": "$days_of_validity",
"creation_date": "$creation_date"
}
}, {
"$match": {
"finalDiff": {
"$lt": 0
}
}
}, {
"$project": {
"days_of_validity": "$days_of_validity",
"creation_date": "$creation_date"
}
})