0
私は 'agendas'という名前のコレクションを持っています。各アジェンダにはネストされたタスクコレクションがあります。
私はタスクコレクションを検索し、その範囲内のタスクを持つすべての議題「アイテム」を見つけるために日付範囲に基づいてマッチを行っています。私はその後、すべてのタスクを削除するフィルタを実行します。したがって、基本的に$ matchと$ filterは同じです。
なぜ私は完全にフィルタされたタスク[]で議題項目を返すのか分かりません。私はアジェンダのアイテムが$ matchで最初にフィルタリングされると思った。
マイクエリ:
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
}
]
}
]
}