skip to Main Content

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


  1. Chosen as BEST ANSWER

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

  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search