使用MongoDB嵌套分组

时间:2013-05-27 11:26:33

标签: mongodb aggregation-framework

给出数据库的形式

[
{ gender: "m", age: 1, name: "A" },
{ gender: "f", age: 2, name: "B" },
{ gender: "m", age: 3, name: "C" },
{ gender: "f", age: 1, name: "D" },
{ gender: "m", age: 2, name: "E" },
{ gender: "f", age: 3, name: "F" },
{ gender: "m", age: 1, name: "G" },
{ gender: "f", age: 2, name: "H" },
{ gender: "m", age: 3, name: "I" },
{ gender: "f", age: 1, name: "J" }
]

我想先按年龄分组,然后按性别分组,以便我得到一个类似

的嵌套结果
[{
    _id: "1",
    children: [
        { _id: "f" },
        { _id: "m" }
    ]
}, {
    _id: "2",
    children: [
        { _id: "f" },
        { _id: "m" }
    ]
}, {
    _id: "3",
    children: [
        { _id: "f" },
        { _id: "m" }
    ]
}]

这是我到目前为止所尝试的内容:

db.example.aggregate(
{ $group: { _id: "$age", children: { $addToSet: {
    age: "$age", gender: "$gender", name: "$name"
}}}},
{ $group: { _id: "$children.gender"}}
)

但是这会返回{_id: null}作为结果。这是可能的,万一是的,怎么样?

1 个答案:

答案 0 :(得分:47)

这样的事情应该这样做;

db.example.aggregate( 
  { 
    $group: { 
      _id:   { age: "$age", gender: "$gender" }, 
      names: { $addToSet: "$name" } 
    } 
  }, 
  { 
    $group: {
      _id: { age: "$_id.age" }, 
      children: { $addToSet: { gender: "$_id.gender", names:"$names" } } 
    } 
  } 
)

...给出了结果;

{
  "_id" : {
    "age" : 1
  },
  "children" : [
    { "gender" : "m", "names" : [ "G", "A" ] },
    { "gender" : "f", "names" : [ "J", "D" ] }
  ]
}, 
...

如果您希望年龄为_id,请将第二个分组的_id替换为;

_id: "$_id.age",