Definition
Calculates the population standard deviation of values across a group of documents. Use $stdDevPop if the values encompass the entire population of data you want to represent and you do not want to generalize.
If the values represent only a sample from the population, use $stdDevSamp instead.
The $stdDevPop accumulator is available in these stages:
Note
Disambiguation
This page describes $stdDevPop when used as an accumulator. Accumulators return an aggregated value across a group of input documents.
You can also use $stdDevPop in these other contexts:
$stdDevPop (expression), which returns the population standard deviation of numeric values in an array.$stdDevPop (window function), which is used in the$setWindowFieldsstage to calculate the population standard deviation of values from documents in a particular window.
Syntax
{ $stdDevPop: <expression> }
For more information on expressions, see Expressions.
Behavior
Result Type
$stdDevPop returns the population standard deviation of the input values as a double.
Non-numeric or Missing Values
$stdDevPop ignores non-numeric values, including missing values. If all input values are non-numeric, $stdDevPop returns null.
Single Value
If the input consists of a single numeric value, $stdDevPop returns 0.
Example
The examples on this page use data from the sample_mflix dataset. For details on how to load this dataset into your self-managed MongoDB deployment, see Load the Sample Dataset. If you made any modifications to the sample databases, you may need to drop and recreate the databases to run the examples on this page.
The following example groups movies by director and returns the five directors with the most varied IMDb ratings, among directors with at least 10 movies.
db.movies.aggregate( [ { $match: { directors: { $exists: true }, "imdb.rating": { $type: "double" } } }, { $unwind: "$directors" }, { $group: { _id: "$directors", movieCount: { $sum: 1 }, stdDevRating: { $stdDevPop: "$imdb.rating" } } }, { $match: { movieCount: { $gte: 10 } } }, { $sort: { stdDevRating: -1 } }, { $limit: 5 } ] )
The preceding pipeline:
Uses
$matchto filter for movies that have adirectorsfield and a numeric IMDb rating.Uses
$unwindto create one document per director per movie, so each director-movie pair is grouped separately.Uses
$groupto group by director, count movies, and computestdDevRatingusing$stdDevPoponimdb.rating.Uses
$matchto keep only directors with at least 10 movies.Uses
$sortto return results in descending order bystdDevRating.Uses
$limitto return the top 5 results.