7 C
London
Tuesday, March 11, 2025
HomeMongoDBAggregation in MongoDBHow to Calculate the Median Value in MongoDB

How to Calculate the Median Value in MongoDB

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 syntax to calculate the median value in MongoDB:

db.teams.find().sort( {"points":1} ).skip(db.teams.count() / 2).limit(1);

Note that in this example we calculate the median value of the points field for the collection named teams.

The following example shows how to use this syntax with a collection teams with the following documents:

db.teams.insertOne({team: "Mavs", position: "Guard", points: 31})
db.teams.insertOne({team: "Spurs", position: "Forward", 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: Calculate the Median Value in MongoDB

We can use the following code to calculate the median value of the ‘points’ field:

db.teams.find().sort( {"points":1} ).skip(db.teams.count() / 2).limit(1);

This returns the following result:

{ _id: ObjectId("61f943e867f1c64a1afb2032"),
  team: 'Warriors',
  position: 'Forward',
  points: 26 }

This tells us that the median value in the “points” field is 26.

We can manually verify this by calculating the median value by hand.

We can see that we have the following values in the “points” column:

Points: 31, 22, 19, 26, 33

First, we can rearrange the values from smallest to largest:

Points: 19, 22, 26, 31, 33

Then the median value is simply the value in the middle, which is 26:

Points: 19, 22, 26, 31, 33

This matches the value that we calculated using MongoDB.

Note: You can find the complete documentation for the find() function here.

Additional Resources

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

MongoDB: How to Count Distinct Values in Field
MongoDB: How to Group By Multiple Fields
MongoDB: How to Group By and Count

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