4.2 C
London
Friday, December 20, 2024
HomeMongoDBAggregation in MongoDBMongoDB: How to Find the Max Value in a Collection

MongoDB: How to Find the Max Value in a Collection

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories