0
我有一个名为'议程'的集合每个议程有一个嵌套的任务集合绞车被引用的对象ID。
我正在做一个关于任务集合的查询,然后根据日期范围进行匹配,找到所有与该范围之间的任务相关的议程“项目”。然后我做一个过滤器来删除所有的任务。所以基本上$ match和$ filter是相同的。
我不确定为什么我要使用完全过滤的任务返回议程项[]。我认为任何议程项目都会首先被$匹配过滤。
我的查询:
db.agendas.aggregate([
{ '$lookup': {
from: 'tasks',
localField: 'tasks',
foreignField: '_id',
as: 'tasks' } },
{ '$match': {
'$and': [
{ 'tasks.status': 'Closed' },
{ 'tasks.date': { '$gte': new ISODate('2017-10-01T05:00:00.000Z') } },
{ 'tasks.date': { '$lte': new ISODate('2017-10-01T05:00:00.000Z') } }
] } },
{ '$limit': 100 },
{ '$project': {
type: 1, description: 1,
tasks: {
'$filter': {
input: '$tasks',
as: 'tasks',
cond: { '$and': [
{ '$eq': [ '$$tasks.status', 'Closed' ] },
{ '$gte': [ '$$tasks.date', new ISODate('2017-10-01T05:00:00.000Z') ] },
{ '$lte': [ '$$tasks.date', new ISODate('2017-10-01T05:00:00.000Z') ] }
] } } } } },
{ '$group': { _id: '$type', agenda: { '$push': '$$ROOT' } } },
{ '$sort': { _id: 1 } } ], {}).pretty()
结果
{
"_id" : "Maintenance",
"agenda" : [
{
"_id" : ObjectId("59d429ba15c67c147f8f3513"),
"description" : "Some new item 4",
"type" : "Maintenance",
"tasks" : [ ]
}
]
}
{
"_id" : "Monitoring",
"agenda" : [
{
"_id" : ObjectId("59d50d36e6de730a6d85019b"),
"description" : "Some new test agenda for Tomski",
"type" : "Monitoring",
"tasks" : [
{
"_id" : ObjectId("59d5378808f51d0c6590c724"),
"status" : "Closed",
"text" : "Some task 2",
"author" : {
"id" : ObjectId("59c09f8a8b4ad70aa4cda487"),
"name" : "Karunik De"
},
"date" : ISODate("2017-10-01T05:00:00Z"),
"created" : ISODate("2017-10-04T19:33:28.560Z"),
"__v" : 0
}
]
}
]
}