[mongodb], How can I get maximum value of a document with many different fields through aggregation? sub field names are same

Viewed 33

I have following document: enter image description here

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 Answers

One option is using $objectToArray to set an array of values and $max to find the item with the maximum value:

db.collection.aggregate([
  {$project: {_id: 0, data: {$objectToArray: "$layouts.nodes"}}},
  {$project: {maxX: {$max: "$data.v.x"}}}
])

See how it works on the playground example

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"}}}}},
    }
Related