Artyom Gribkov
Artyom Gribkov

Reputation: 13

How to make group in mongodb?

I have collection with documents like this:

{ "_id" : ObjectId("56e17f2db292c9151a8b459b"), "title" : "test title", "category" : "test category", "pubDate" : "1457599100", "code" : "ZZZ" },
{ "_id" : ObjectId("56e17f2db292c9151a8b459b"), "title" : "test 2 title", "category" : "test 2 category", "pubDate" : "1457599200", "code" : "ZZZ" }

How to make the grouping to get output something like this:

{
  "ZZZ": {
    "items": {
      0: { "_id" : ObjectId("56e17f2db292c9151a8b459b"), "title" : "test title", "category" : "test category", "pubDate" : "1457599100"},
      1: { "_id" : ObjectId("56e17f2db292c9151a8b459b"), "title" : "test 2 title", "category" : "test 2 category", "pubDate" : "1457599100"}
    }
  }
}

Upvotes: 1

Views: 62

Answers (1)

Matt Prelude
Matt Prelude

Reputation: 912

This should give you similar to what you're looking for:

db.collection.aggregate([{ $group : { _id : "$code", items: { $push: "$$ROOT" } } }])

It will return:

{
  "_id" : "ZZZ",
  "items" :
     [
       { "_id" : ObjectId("56e17f2db292c9151a8b459b"), "title" : "test title", "category" : "test category", "pubDate" : "1457599100", "code" : "ZZZ" },
       { "_id" : ObjectId("56e17f2db292c9151a8b459b"), "title" : "test 2 title", "category" : "test 2 category", "pubDate" : "1457599200", "code" : "ZZZ" }
     ]
}

Documentation can be found under $group aggregation.

Upvotes: 1

Related Questions