需要使用聚合管道来获取文档
-
$ifNull
- 如果接受的日期为空,则设置当前日期
-
$addFields
- 添加字段,并将现有文档添加到from
fromDays
toDays
- 过滤器
$redact
-
$redact
- 在字段和过滤器内匹配
-
$project
- 排除阶段中添加的字段$addFields
mongo query
db.t1.aggregate([
{$addFields : {
from : {$ifNull : ["$acceptedDate", new Date()]}
}},
{$addFields: {
fromDays : {$sum : [{$multiply : [365, {$year : "$from"}]}, {$dayOfYear : "$from"}]},
toDays : {$sum : [{$multiply : [365, {$year : "$lastVisit"}]}, {$dayOfYear : "$lastVisit"}]}
}},
{ $redact: {
$cond: {
if: {$lte : [{$subtract : ["$fromDays", "$toDays"]}, 15]},
then: "$$DESCEND",
else: "$$PRUNE"
}
}
},
{$project : {from:0, fromDays:0, toDays:0}}
])
样品采集
> db.t1.find().pretty()
{
"_id" : "someid",
"factoryNumber" : 123,
"factoryName" : "some factory name",
"visitType" : "audit",
"personelId" : "somePersonel",
"lastVisit" : ISODate("2018-10-30T00:00:00Z"),
"acceptedDate" : ISODate("2018-11-16T00:00:00Z")
}
{
"_id" : "someotherid",
"factoryNumber" : 123,
"factoryName" : "some factory name",
"visitType" : "audit",
"personelId" : "somePersonel",
"lastVisit" : ISODate("2018-10-30T00:00:00Z")
}
结果与最小 150 天
> db.t1.aggregate([ {$addFields : { from : {$ifNull : ["$acceptedDate", new Date()]} }}, {$addFields: { fromDays : {$sum : [{$multiply : [365, {$year : "$from"}]}, {$dayOfYear : "$from"}]}, toDays : {$sum : [{$multiply : [365, {$year : "$lastVisit"}]}, {$dayOfYear : "$lastVisit"}]} }}, { $redact: { $cond: { if: {$lte : [{$subtract : ["$fromDays", "$toDays"]}, 150]}, then: "$$DESCEND", else: "$$PRUNE" } } }, {$project : {from:0, fromDays:0, toDays:0}} ]).pretty()
{
"_id" : "someid",
"factoryNumber" : 123,
"factoryName" : "some factory name",
"visitType" : "audit",
"personelId" : "somePersonel",
"lastVisit" : ISODate("2018-10-30T00:00:00Z"),
"acceptedDate" : ISODate("2018-11-16T00:00:00Z")
}
{
"_id" : "someotherid",
"factoryNumber" : 123,
"factoryName" : "some factory name",
"visitType" : "audit",
"personelId" : "somePersonel",
"lastVisit" : ISODate("2018-10-30T00:00:00Z")
}
>
将 mongo 聚合查询转换为春季 mongodb 查询