'MongoDB Aggregate Select ALL fields while grouping them by only one specific field

I'm using Mongoose 6.2.9 and MongoDB v.4.4.13

I have this schema user_relationships

_id - Object Id
parent_user - Object Id
child_user - Object Id
relationship - String

Basically I want to select * from user_relationships group_by = parent_user

How can I achieve this by using aggregatation?



Solution 1:[1]

db.getCollection('user_relationships').aggregate([{
        $group: {
            "_id": "$parent_user",
            "childrens": {
                    $push: "$$ROOT"
             }
        }
}, {
        $project: {
                "parent": "$_id",
                 _id: 0,
                "childrens": 1
        }
}])

You can get data using $group only this aggregation, I just customized results using $project

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 krbalaji