Sergei Kirsanov
Sergei Kirsanov

Reputation: 49

Grouping by ID in mongoDB

Can anyone help me with the following aggregate operation in mongodb: having a collection of items with ids and group ids, group them by group ids. For example, for collection of items:

{
    "id": 1,
    "group_id": 10,
    "data": "some_data",
    "name": "first"
},
{
    "id": 2,
    "group_id": 10,
    "data": "some_data",
    "name": "second"
},
{
    "id": 3
    "group_id": 20,
    "data": "some_data",
    "name": "third"
}

Create new collection of groups with the following structure:

    {
    "id": 10,
    "items": [
        {
            "id": 1,
            "group_id": 10,
            "data": "some_data",
            "name": "first"
        },
        {
            "id": 2,
            "group_id": 10,
            "data": "some_data",
            "name": "second"
        }
    ]
},
{
    "id": 10,
    "items": [
        {
            "id": 2,
            "group_id": 20,
            "data": "some_data",
            "name": "third"
        }
    ]
}

The corresponding snippet with Java and spring-data-mongodb will also be appreciated. In fact I'm doing the same right now with Java and want to move this logic to mongo for paging optimisation.

Upvotes: 0

Views: 138

Answers (1)

HoefMeistert
HoefMeistert

Reputation: 1200

You can do it with the folowwing simple group aggregation:

db.table.aggregate(
  [
    {
      $group: {
       _id : "$group_id",
       items : { "$push" : "$$ROOT" }
      }
    }
  ]
);

When you want to output the data from the aggregation into a new collection use the $out operator

Upvotes: 2

Related Questions