Reshape MongoDB aggregation result to field value documents -


i have data collection containing data in following shape:

[ {_id: "1",    aa1: 45, aa2: 56,    bb1: 90, bb2: 78,    cc1: 34, cc2: 98 },   {_id: "2",    aa1: 76, aa2: 56,    bb1: 45, bb2: 67,    cc1: 75, cc2: 87 } ] 

on data perform mongodb aggregation pipeline:

db.colleciton.aggregate([  { $project: {              "_id": "$_id",              "aaa": { $avg: ["$aa1","$aa2"] },              "bbb": { $avg: ["$bb1","$bb2"] },              "ccc": { $avg: ["$cc1","$cc2"] }              }  },   { $group: {              "_id": "avgcalc",              "aaa": { $avg: "$aaa" },              "bbb": { $avg: "$bbb" },              "ccc": { $avg: "$ccc" }              }       } ]) 

that gives result in format:

[ {_id: "avgcalc",    aaa: 67,    bbb: 55,    ccc: 90} ] 

i convert in aggregation give result as:

[ {field: "aaa", value: 67},    {field: "bbb", value: 55},   {field: "ccc", value: 90} ] 

is there way achieve aggregation? add final stage in pipeline. tried adding $project stage no success.

this pipeline should give desired result

db.getcollection('yourcoll').aggregate([  {      $project: {         "_id": "$_id",         "aaa": { $avg: ["$aa1","$aa2"] },         "bbb": { $avg: ["$bb1","$bb2"] },         "ccc": { $avg: ["$cc1","$cc2"] }      }  },   {      $group: {         "_id": "avgcalc",         "aaa": { $avg: "$aaa" },         "bbb": { $avg: "$bbb" },         "ccc": { $avg: "$ccc" }      }       },  {     $project: {         "items": [              {name: {$literal: "aaa"}, value: "$aaa"},             {name: {$literal: "bbb"}, value: "$bbb"},             {name: {$literal: "ccc"}, value: "$ccc"}         ]     }  },  {      $unwind: {          path: "$items"      }  },  {      $project: {          _id: 0,          field: "$items.name",          value: "$items.value"      }  } ]) 

for sample data previous output

/* 1 */ {     "_id" : "avgcalc",     "aaa" : 58.25,     "bbb" : 70.0,     "ccc" : 73.5 } 

and new pipeline output

/* 1 */ {     "field" : "aaa",     "value" : 58.25 }  /* 2 */ {     "field" : "bbb",     "value" : 70.0 }  /* 3 */ {     "field" : "ccc",     "value" : 73.5 } 

Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -