Select * group by in mongo aggregation

后端 未结 4 1428
名媛妹妹
名媛妹妹 2021-02-08 02:25

I am trying to do something that I think is quite simple. Suppose I have a series of records in mongo that have a common key, and variable number of attributes. I want to select

4条回答
  •  清歌不尽
    2021-02-08 03:02

    If you want to combine the attributes, you'll need to add those to the group. For example, using $addToSet to find the unique values of the x,y,z attributes grouped by each name:

    db.data.aggregate(
        { $group : {
                _id : "$Name",
                x: { $addToSet: "$x" },
                y: { $addToSet: "$y" },
                z: { $addToSet: "$z" },
        }}
    )
    

    Returns:

    {
        "result" : [
            {
                "_id" : "Rob",
                "x" : [
                    12
                ],
                "y" : [
                    2
                ],
                "z" : [ ]
            },
            {
                "_id" : "George",
                "x" : [
                    5
                ],
                "y" : [
                    3
                ],
                "z" : [
                    9
                ]
            }
        ],
        "ok" : 1
    }
    

提交回复
热议问题