18

Given a database the form of

[
{ 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" }
]

I want to first group by age and secondly group by gender so that I get a nested result looking something like

[{
    _id: "1",
    children: [
        { _id: "f" },
        { _id: "m" }
    ]
}, {
    _id: "2",
    children: [
        { _id: "f" },
        { _id: "m" }
    ]
}, {
    _id: "3",
    children: [
        { _id: "f" },
        { _id: "m" }
    ]
}]

Here is what I tried so far:

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

But this returns an {_id: null} as its result. Is this possible and in case yes, how?

4

1 回答 1

51

像这样的事情应该这样做;

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", 
于 2013-05-27T11:55:30.173 回答