I'm attempting to extract the highest value from an child Array within Object, that is within a parent Array - in a single MongoDB document.
The child Array is called data contained within the list parent Array, where i'm trying to extract the highest number, when compared to the rest of the same values.
I've tried using $Group and $max (example below) among other things - however not getting much success. - I am getting an array returned with all the number values: [2,3]
How do I search through the list Array and data Array to return the highest number?
Expected Output for the below example: {output: 3}
Example in MongoPlayground: https://mongoplayground.net/p/qw9Kz_WVYiS
Mongo DB Setup and Documents
db={
"groups": [
{
"_id": ObjectId("602ed22af42c404096407dda"),
"groupName": "Name"
}
],
"inventory": [
{
"_id": ObjectId("602ed22af42c404096407ddc"),
"linkedGroup": ObjectId("602ed22af42c404096407dda"),
"list": [
{
"_id": ObjectId("602eeb0621a11045638b7082"),
"data": {
"number": 2
},
},
{
"_id": ObjectId("602eec75c37147459ed7b12c"),
"data": {
"number": 3
}
}
]
}
]
}
Query
db.groups.aggregate([
{
"$lookup": {
"from": "inventory",
"localField": "_id",
"foreignField": "linkedGroup",
"as": "inventory_links"
}
},
{
$group: {
_id: 1,
output: {
$max: "$inventory_links.list.data.number"
},
},
}
])