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

回答

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

比較之下,看起來對於一個任務相匹配的標準。因此,您可以讓單個任務匹配所有標準或匹配每個條件的三個不同任務以返回文檔。

{ 
    "$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