Nixit Patel
Nixit Patel

Reputation: 4445

$group result as the key value pair mongo db

In the pipeline stage before the $group stage computed the document like bellow

cycle_id | entity1 | entity 2
   1     |    0    |    1
   1     |    1    |    5
   2     |    0    |    3

I am able to group them using bellow script

{ 
        "$group" : { 
            "_id" : "$cycle_id", 
            "entity1" : { 
                "$sum" : "$entity1"
            }, 
            "entity2" : { 
                "$sum" : "$entity3"
            }, 
            "entity3" : { 
                "$sum" : "$entity3"
            }
        }
    }

This generated output like bellow:

cycle_id | entity1 | entity 2
   1     |    1    |    6
   2     |    0    |    3

but what I am looking for is something where I can project it like an array of key-value pair

{
 1:{
  entity1: 1,
  entiry2: 6
 },
 2:{
  entity1: 3,
  entiry2: 4
 }
}

Is there a way I can achieve the above result. I tried to look around $arrayToObject but wasn't quite successful with that yet.

Thanks, Nixit

Upvotes: 0

Views: 1669

Answers (1)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17915

Query :

db.collection.aggregate([
    /** Group without any condition and merge all documents (Converted objects) into an object */
    {
      $group: {
        _id: "",
        data: {
          $mergeObjects: {
            $arrayToObject: [ [ { k: { $toString: "$_id" }, v: { "entity1": "$entity1", "entity2": "$entity2" } } ] ]
          }
        }
      }
    },
    /** Replace `data` field as a root of the document */
    {
      $replaceRoot: { newRoot: "$data" }
    }
  ])

Test : mongoplayground

Ref : aggregation-pipeline

Upvotes: 3

Related Questions