vit_vostotskiy
vit_vostotskiy

Reputation: 83

Convert values to keys in mongodb aggregation

As far as MongoDB provides $group approach in aggregate pipeline, it returns list of documents, where _id keeps some "distinct" grouping value and other field keeps array of documents, grouped by given condition.

What I want is to return a single document where the properties are the results of the aggregation.

Example collection:

{author: "Author1", title: "Title1"}
{author: "Author2", title: "Title2"}
{author: "Author2", title: "Title3"}

The aggregation

db.getCollection('books').aggregate([ 
    {"$group": {
           _id: "$author",
           books: { $push: "$$ROOT" }
          }
    }
])

This gives me the following output:

{_id: 'Author1', books: [{author: "Author1", title: "Title1"}]},
{_id: 'Author2', books: [{author: "Author2", title: "Title2"}, {author: "Author2", title: "Title3"}]}

But i would like to get the results as one single object like this:

{
  Author1: [
    {author: "Author1", title: "Title1"}
  ],
  Author2: [ 
    {author: "Author2", title: "Title2"},
    {author: "Author2", title: "Title3"}
  ]
}

In simple words, i want to use _id property as new field in resulting document, and proper $group values for specific _id must be value of new variable.

If somebody faced with such a queries, please, assist with that or give some clues how to solve it. Thanks in advance.

Upvotes: 2

Views: 1843

Answers (1)

Ashh
Ashh

Reputation: 46481

You can try below aggregation

db.getCollection('books').aggregate([ 
  { "$group": {
    "_id": "$author",
    "books": { "$push": "$$ROOT" }
  }},
  { "$group": {
    "_id": null,
    "data": {
      "$push": { "k": "$_id", "v": "$books" }
    }
  }},
  { "$replaceRoot": {
    "newRoot": { "$arrayToObject": "$data" }
  }}
])

Upvotes: 4

Related Questions