Sample Example Documents:
[
{"subdoc": {"val":100,"extraVal":300}},
{"subdoc": { "val":100 } // extraVal is not present in this one
]
Desired Outcome: after the aggregation process:
{
"largest": // The entire first item with 300 as highest value
"smallest": // The entire second item with 100 as smallest average
"average": 150 // Average of 200 from first item and 100 from second item makes 150
}
Approach Used:
{ $sort: { 'subdoc.val': -1 } },
{
$group: {
_id: null,
average: { $avg: '$subdoc.val' },
items: { $push: '$$ROOT' },
},
},
{ $set: { largest: { $first: '$items' } } },
{ $set: { smallest: { $last: '$items' } } },
{ $project: { largest: 1, smallest: 1, average: 1 } },
Current Approach does not account for extraVal
field.
Unable to find a way to incorporate a "larger one" logic
Considering: average:
{ $max: { $greater: ['$subdoc.val', 'subdoc.extraVal'] }},
IMPORTANT NOTE: Optional presence of extraVal
field.