Nested grouping with MongoDB

后端 未结 1 1705
你的背包
你的背包 2021-01-31 00:00

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:          


        
相关标签:
1条回答
  • 2021-01-31 00:25

    Something like this should do it;

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

    ...which gives the result;

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

    If you want the age as _id as in your example, just replace the second grouping's _id by;

    _id: "$_id.age", 
    
    0 讨论(0)
提交回复
热议问题