Definition
Returns the population standard deviation of values from documents in a particular window.
Note
Disambiguation
This page describes $stdDevPop when used as a window
function.
You can also use $stdDevPop in these other contexts:
$stdDevPop (accumulator), which returns the population standard deviation of values across a group of documents.$stdDevPop (expression), which returns the population standard deviation of numeric values in an array.
Syntax
{ $setWindowFields: { ... output: { <field>: { $stdDevPop: <expression> } } } }
Behavior
Result Type
$stdDevPop returns the population standard deviation of the input values as a double.
Non-Numeric Values
The $stdDevPop window function ignores non-numeric values. If the window contains no numeric values, $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.
This example uses $setWindowFields to add to each document a field that contains the running population standard deviation of IMDb ratings for Musicals from 2009 and 2010.
db.movies.aggregate( [ { $match: { genres: "Musical", year: { $in: [ 2009, 2010 ] }, "imdb.rating": { $type: "double" } } }, { $setWindowFields: { partitionBy: "$year", sortBy: { title: 1 }, output: { stdDevPopRatingInYear: { $stdDevPop: "$imdb.rating", window: { documents: [ "unbounded", "current" ] } }, rankInYear: { $documentNumber: {} } } } }, { $project: { _id: 0, title: 1, year: 1, "imdb.rating": 1, stdDevPopRatingInYear: 1, rankInYear: 1 } }, { $sort: { year: 1, title: 1 } } ] )
The preceding pipeline:
Uses
$matchto filter for Musicals from 2009 and 2010 with a numeric IMDb rating.Uses
$setWindowFieldsto partition movies byyearand sort them bytitle. The stage uses$stdDevPopwith a documents window of[ "unbounded", "current" ]to createstdDevPopRatingInYear. ThestdDevPopRatingInYearfield holds the running population standard deviation ofimdb.ratingfrom the start of the partition to the current document.$documentNumberassigns a per-partition row number (rankInYear) to each document.Uses
$projectto includetitle,year,imdb,stdDevPopRatingInYear, andrankInYearin the output.Uses
$sortto sort the results by year and title.