A
A
Artem Gribkov2016-03-15 13:12:45
PHP
Artem Gribkov, 2016-03-15 13:12:45

How to do grouping in mongodb?

There is a collection with documents of the form:

{ "_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 grouping to get something like this in the output:
{
  "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"}
    }
  }
}

At the same time, it is still desirable to sort by pubDate

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem Gribkov, 2016-03-15
@L1Qu0R

Answered on stackoverflow:

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

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question