Mongo聚合列表

时间:2014-03-03 01:27:43

标签: mongodb aggregation-framework

我有这样的集合:

{id:1, name: "fluffy", 
  toys: [{id: "mouse", colors: ['red', 'green']}, 
         {id: "yarn", colors: ['blue', 'green']]
},

{id:2, name: "rex", 
  toys: [{id: "bone", colors: ['gray']}]
}  

我希望看到这样的结果:

[
  {id: 1, name:"fluffy", toyColors:["red", "green", "blue"]},
  {id: 2, name:"rex", toyColors:["gray"]} 
]

我尝试过类似的东西,但是我得到了“列表清单”,而不是玩具颜色的一个大清单。另外,我不知道如何用这样的查询选择宠物名称。

db.pets.aggregate({$group:{_id: "$id", toyColors: {$addToSet: "$toys.colors"}}})

2 个答案:

答案 0 :(得分:1)

您应该使用双$unwind

db.pets.aggregate(
    { $unwind: "$toys" },
    { $unwind: "$toys.colors" },
    { $group: 
        {
            _id: "$_id",
            toyColors: {$addToSet: "$toys.colors"}      
        } 
    }
)

答案 1 :(得分:1)

您需要使用$unwind

  db.pets.aggregate([
        // Unwind the array
        {$unwind: "$toys"},
        // Unwind the inner array
        {$unwind: "$toys.colors"},
        {$group:{_id: 
            { _id: "$id", name: "$name"},
            toyColors: {$addToSet: "$toys.colors"}}
        },
        {$project: { 
            _id: 0,
            _id: "$_id._id",
            name: "$_id.name",
            toyColors: 1
        }}
  ])

还要在分组中添加名称,并在$ project中添加更好的结果。

相关问题