Calculate the Median Value in MongoDB?

The median value of a set of data in MongoDB can be calculated using the $group and $project operators. The $group operator is used to group the data together and the $project operator is used to project the median value from the grouped data. The expression {$median: “$”} is used to calculate the median value of a field in the data set. This expression is then used in the $project operator to get the median value.


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:

This matches the value that we calculated using MongoDB.

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

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

x