Home > front end >  [mongodb], How can I get maximum value of a document with many different fields through aggregation?
[mongodb], How can I get maximum value of a document with many different fields through aggregation?

Time:07-19

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)

CodePudding user response:

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

  • Related