2017-07-02 248 views
0

有人跟我在一起我是一个光,我不受欢迎。聚合MongoDB结果组合

我不知道我会做这样的调整与一群

db.users.aggregate([ 
     { $match : { '_id': ObjectId('5956a6361b9f673dc629c9a6') } }, 
     { '$unwind': { 'path': '$profile', 'preserveNullAndEmptyArrays': true } }, 
     {$lookup: { 
       'from': 'institution', 
       'localField': 'profile.departament', 
       'foreignField': 'departament._id', 
       'as': 'Institution' 
      } 
     }, 
     { '$unwind': { 'path': '$Institution', 'preserveNullAndEmptyArrays': true } }, 

     {$project: { 
      'Profile':{ 
       'name' : '$name', 
       'photo': '$photo', 
       'nickname' : '$nickname', 
       'institution' : {name: '$Institution.name', photo: '$Institution.photo'},   
       'departments' : {title : '$Institution.departament.title', category: '$Institution.departament.category'} , 
      } 
      } 
     }, 

     { $group : { 
       '_id' : '$_id', 
       'profile': { $push : '$Profile' }, 

      } 
     }, 




    ]) 

我不能做组“机构” O结果就是这个样子

"departments" : { 
      "title" : [ 
       "Terror by africa", 
       "Africa" 
      ], 
      "category" : [ 
       "Sub-15", 
       "Sub-20" 
      ] 
     } 

正如我'试图让不必使用阵列位置

"departments" : { 
      "title" : [{ 
       name: "Terror by africa", 
       category: "Sub-15", 
      },{ 
       name: "Africa", 
       category: "Sub-20", 
      }], 

     } 

回答

1

您可以删除$group阶段和更新departments预测使用$map来转换密钥。

喜欢的东西

{ 
    departments: { 
     $map: { 
      input: "$Institution.departament", 
      as: "departament", 
      in: { 
       name: '$$departament.title', 
       category: '$$departament.category' 
      } 
     } 
    } 
}