Reshape MongoDB aggregation result to field value documents Reshape MongoDB aggregation result to field value documents mongodb mongodb

Reshape MongoDB aggregation result to field value documents


This pipeline should give you the 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 your sample data the previous output was

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

and with the new pipeline the output is like this

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