Home » How to Calculate the Median Value in MongoDB

How to Calculate the Median Value in MongoDB

by Tutor Aspire

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

You may also like