Home » MongoDB: How to Find the Max Value in a Collection

MongoDB: How to Find the Max Value in a Collection

by Tutor Aspire

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}) 

This query returns the following result:

[ 33 ] 

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

Additional Resources

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

MongoDB: How to Group By and Count
MongoDB: How to Group By Multiple Fields
MongoDB: How to Check if Field Contains a String

You may also like