1

我有一個蒙戈查詢選擇字段作爲數組貓鼬/ MongoDB的聚集值

db.memberships.aggregate([{ 
     '$match': { 
      unit: new ObjectId('566fbaa1e63225b10bacac44') 
     } 
    }, 

    { 
     '$lookup': { 
      from: 'seasons', 
      localField: 'season', 
      foreignField: '_id', 
      as: 'season' 
     } 
    }, 

    { 
     '$unwind': '$season' 
    }, 
    { 
     '$project': { 
      season: { 
       'name': '$season.name', 
       'id': '$season._id' 
      } 
     } 
    }, 
    { 
     '$group': { 
      _id: '$_id', 
      'season': { 
       '$addToSet': '$season' 
      } 
     } 
    }, 

]); 

導致

[ 
    { 
     "_id": ObjectId("56a0e5a860d8a6e41eda2ea3"), 
     "season": [{ 
      "name": "Summer", 
      "id": ObjectId("56a0d6c692c26b8c019a2758") 
     }] 
    }, 
    { 
     "_id": ObjectId("56a0e56d60d8a6e41eda2e9e"), 
     "season": [{ 
      "name": "Summer", 
      "id": ObjectId("56a0d6c692c26b8c019a2758") 
     }] 
    }, 
    { 
     "_id": ObjectId("56a0e53860d8a6e41eda2e9a"), 
     "season": [{ 
      "name": "Summer", 
      "id": ObjectId("56a0d6c692c26b8c019a2758") 
     }] 
    }, 

    { 
     "_id": ObjectId("56a0e4d660d8a6e41eda2e94"), 
     "season": [{ 
      "name": "Winter", 
      "id": ObjectId("5680dc01ba1e41f5066526fa") 
     }] 
    } 
] 

我需要得到的結果在這種格式

{ 
    _id: [ 
     // ids here 
    ], 
    seasons: [{ 
      id: '56a0d6c692c26b8c019a2758', 
      'name': 'Summer' 
     }, 
     { 
      id: '5680dc01ba1e41f5066526fa', 
      'name': 'Winter' 
     } 
    ] 
} 

查詢必須返回具有2個屬性idseason的單個文檔。季節必須是一系列獨特的季節。每個賽季都應該包含一個id和一個名字。感謝幫助!

回答

1

重塑您的管道與$group步驟有null_id值來計算累積值的所有輸入文檔作爲一個整體,從而創建ID字段作爲一切的唯一ID的數組:

var pipeline = [ 
    { 
     '$match': { 
      unit: new ObjectId('566fbaa1e63225b10bacac44') 
     } 
    }, 

    { 
     '$lookup': { 
      from: 'seasons', localField: 'season', foreignField: '_id', as: 'season' 
     } 
    }, 
    { 
     '$unwind' : '$season' 
    }, 
    { 
     '$project': { 
      season: {'name': '$season.name', 'id' : '$season._id'} 
     } 
    }, 
     { 
     '$group': { 
      "_id": null, 
      "id": { "$addToSet": "$_id" }, 
      'season': { 
       '$addToSet': '$season' 
      } 
     } 
    }  
]; 
db.memberships.aggregate(pipeline); 
+1

它的工作原理,謝謝! – styopdev