I have following document:
Below layouts.nodes, there are many node fields(no limit), and I want to find the maximum x value in these nodes. How can I achieve this? (this specific document format is a configuration of a frontend library)
2
The go stage code example:
matchStage := bson.D{{"$match", bson.D{{"_id", "1"}}}} projectStage := bson.D{{"$project", bson.D{{"_id", 0}, {"nodes", "$layouts.nodes"}}}} transformStage := bson.D{ {"$set", bson.D{{"data", bson.D{{"$objectToArray", "$nodes"}}}}}, } calcStage := bson.D{ {"$set", bson.D{{"maxX", bson.D{{"$max", "$data.v.x"}}}}}, }
One option is using $objectToArray to set an array of values and $max to find the item with the maximum value:
$objectToArray
$max
db.collection.aggregate([ {$project: {_id: 0, data: {$objectToArray: "$layouts.nodes"}}}, {$project: {maxX: {$max: "$data.v.x"}}} ])
See how it works on the playground example
Click here to cancel reply.
2
Answers
The go stage code example:
One option is using
$objectToArray
to set an array of values and$max
to find the item with the maximum value:See how it works on the playground example