2017-10-10 3 views
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 
           } 
         ] 
       } 
     ] 
} 

答えて

1

あなたは複数の条件を持っていて、各タスクのすべての基準を適用したいとき$elemMatchを使用する必要があります。

{ 
    "$match": { 
    "tasks": { 
     "$elemMatch": { 
     "status": "Closed", 
     "date": { 
      "$gte": new ISODate('2017-10-01T05:00:00.000Z'), 
      "$lte": new ISODate('2017-10-01T05:00:00.000Z') 
     } 
     } 
    } 
    } 
} 

もっとhere

よう

何かは、各条件に一致する一つのタスクを探し、以下のと比較してください。したがって、すべての条件に一致する単一のタスク、または各条件に一致する3つの異なるタスクを持つことで、ドキュメントを返すことができます。

{ 
    "$match": { 
    "tasks.status": "Closed", 
    "tasks.date": { 
     "$gte": new ISODate('2017-10-01T05:00:00.000Z'), 
     "$lte": new ISODate('2017-10-01T05:00:00.000Z') 
    } 
    } 
} 

もっとhere

関連する問題