$covariancePop
New from version 8.0.2.
The $covariancePop operator in Amazon DocumentDB returns the population covariance of two numeric expressions. It is a window operator that is used only in the $setWindowFields stage; it is not valid in the $group or $bucket stages. You specify the operator under the stage's output field, and optionally define the window boundaries with a window document.
Parameters
-
$covariancePoptakes a two-element array[ <expression1>, <expression2> ], where each element is a numeric expression (a field path such as"$x", an expression, or a constant). It returns the population covariance of the two expressions across the documents in the window.
Example (MongoDB Shell)
The following example partitions the documents by series, sorts each partition by t, and computes the population covariance of x and y over the whole partition.
Create sample documents
db.measurements.insertMany([ { _id: 1, series: "A", t: 1, x: 1, y: 2 }, { _id: 2, series: "A", t: 2, x: 2, y: 5 }, { _id: 3, series: "A", t: 3, x: 3, y: 8 }, { _id: 4, series: "B", t: 1, x: 1, y: 8 }, { _id: 5, series: "B", t: 2, x: 2, y: 5 }, { _id: 6, series: "B", t: 3, x: 3, y: 2 } ]);
Query example
db.measurements.aggregate([ { $setWindowFields: { partitionBy: "$series", sortBy: { t: 1 }, output: { covariance: { $covariancePop: [ "$x", "$y" ], window: { documents: ["unbounded", "unbounded"] } } } } } ]);
Output
[
{ "_id": 1, "series": "A", "t": 1, "x": 1, "y": 2, "covariance": 2 },
{ "_id": 2, "series": "A", "t": 2, "x": 2, "y": 5, "covariance": 2 },
{ "_id": 3, "series": "A", "t": 3, "x": 3, "y": 8, "covariance": 2 },
{ "_id": 4, "series": "B", "t": 1, "x": 1, "y": 8, "covariance": -2 },
{ "_id": 5, "series": "B", "t": 2, "x": 2, "y": 5, "covariance": -2 },
{ "_id": 6, "series": "B", "t": 3, "x": 3, "y": 2, "covariance": -2 }
]
Every document in a partition receives the same covariance, the population covariance of x and y across all documents in that partition: 2 for series A (x and y increase together) and -2 for series B (y decreases as x increases).
Code examples
To view a code example for using the $covariancePop operator in the $setWindowFields stage, choose the tab for the language that you want to use: