汇总内部字段MongoDB

时间:2018-08-20 14:53:57

标签: mongodb aggregation-framework

我有以下两种情况:

skills : ([
{_id: NumberInt(0), 
name: 'Creativity', 
description: 'description', 
type: 'soft', 
categories: [NumberInt(0), NumberInt(2)]}
...

和约会技能:

db.dateskill.insertMany([
{ _id: NumberInt(0), skills:[
    { _id: NumberInt(18), owned: NumberInt(1), planned: '2018/05',  achieved: '',  expire: '2018/02',score: NumberInt(100), expYear: NumberInt(3)}, 
    { _id: NumberInt(1), owned: NumberInt(1), planned: '2018/07',  achieved: '2018/05',  expire: '',score: NumberInt(100), expYear: NumberInt(5)}, 
    { _id: NumberInt(9), owned: NumberInt(1), planned: '2018/04',  achieved: '2018/05',  expire: '2019/10',score: NumberInt(100), expYear: NumberInt(1)}, 
    { _id: NumberInt(10), owned: NumberInt(1), planned: '2018/10',  achieved: '',  expire: '',score: NumberInt(66), expYear: NumberInt(1)}, 
    { _id: NumberInt(17), owned: NumberInt(1), planned: '',  achieved: '2017/05',  expire: '2018/09',score: NumberInt(33), expYear: NumberInt(1)}, 
    { _id: NumberInt(2), owned: NumberInt(1), planned: '',  achieved: '2017/05',  expire: '2019/05',score: NumberInt(66), expYear: NumberInt(1)}, 
    { _id: NumberInt(4), owned: NumberInt(0), planned:'2018/05',  achieved: '',  expire: '',score: NumberInt(0), expYear: NumberInt(0)}, 
    { _id: NumberInt(11), owned: NumberInt(0), planned: '',  achieved: '',  expire: '',score: NumberInt(0), expYear: NumberInt(0)}, 
    { _id: NumberInt(12), owned: NumberInt(0), planned: '',  achieved: '',  expire: '',score: NumberInt(0), expYear: NumberInt(0)}, 
    { _id: NumberInt(7), owned: NumberInt(0), planned: '2019/10',  achieved: '',  expire: '',score: NumberInt(0), expYear: NumberInt(0)}, 
    { _id: NumberInt(8), owned: NumberInt(0), planned: '2020/02',  achieved: '',  expire: '',score: NumberInt(0), expYear: NumberInt(0)}
    ]}
...

如何汇总这两个集合以将“ kills.name”和“ kills.name”和“ kills.type”字段“合并”?

我正在寻找这样的解决方案:

{ _id: NumberInt(0), skills:[
       { _id: NumberInt(18), 
       type: 'hard', 
       name: 'Creativity',
        owned: NumberInt(1), 
       planned: '2018/05',  
       achieved: '',  
       expire: '2018/02',
       score: NumberInt(100), expYear: NumberInt(3)},
      { _id: NumberInt(18), 
       type: 'soft' , 
       name : 'Other skill name',
      owned: NumberInt(1), 
       planned: '2018/05',  
       achieved: '',  
       expire: '2018/02',
   score: NumberInt(100), 
       expYear: NumberInt(3)} 
.....

谢谢。

1 个答案:

答案 0 :(得分:0)

您可以使用以下汇总。

db.dateskill.aggregate([
  {"$unwind":"$skills"},
  {"$lookup":{
    "from":"skills",
    "localField":"skills._id",
    "foreignField":"_id",
    "as":"skill_lookup"
  }},
  {"$unwind":"$skill_lookup"},
  {"$addFields":{"skills.name":"$skill_lookup.name","skills.type":"$skill_lookup.type"}},
  {"$group":{"_id":"$_id","skills":{"$push":"$skills"}}}
])