How would you find the Max Value in a Collection?

To find the max value in a collection, you would iterate through the collection and compare each element to the next element. When you find an element with a value larger than the current max value, you would set the current max value to the value of that element. This process would continue until all elements in the collection have been compared, at which point the current max value will be the max value of the collection.


You can use the following methods to find the max value of a field in MongoDB:

Method 1: Return Document that Contains Max Value

db.teams.find().sort({"field":-1}).limit(1)

This chunk of code sorts every document in the collection in descending order based on a specific field and then returns only the first document.

Method 2: Return Only the Max Value

db.teams.find().sort({"field":-1}).limit(1).toArray().map(function(u){return u.field})

The following examples show how to use each method with a collection teams with the following documents:

db.teams.insertOne({team: "Mavs", position: "Guard", points: 31})
db.teams.insertOne({team: "Spurs", position: "Guard", points: 22})
db.teams.insertOne({team: "Rockets", position: "Center", points: 19})
db.teams.insertOne({team: "Warriors", position: "Forward", points: 26})
db.teams.insertOne({team: "Cavs", position: "Guard", points: 33})

Example 1: Return Document that Contains Max Value

We can use the following code to return the document that contains the max value in the “points” field:

db.teams.find().sort({"points":-1}).limit(1) 

This query returns the following document:

{ _id: ObjectId("618285361a42e92ac9ccd2c6"),
  team: 'Cavs',
  position: 'Guard',
  points: 33 }

This document is returned because it contains the highest value (33) in the “points” field out of all of the documents.

Example 2: Return Only the Max Value

We can use the following code to return just the max value in the “points” field out of all of the documents:

db.teams.find().sort({"points":-1}).limit(1).toArray().map(function(u){return u.points}) 

[ 33 ] 

Notice that only the max value itself (33) is returned instead of the entire document that contains the max value.

The following tutorials explain how to perform other common operations in MongoDB:

x