$covariancePop

Calculates the population covariance of two numerical expressions within a specified document window, used in statistical analysis to measure how two variables change together.

Syntax

{ $covariancePop: [<numericalExpression1>, <numericalExpression2>] }

Parameters

numericalExpression1objectrequired

First numerical expression for covariance calculation within the document window

numericalExpression2objectrequired

Second numerical expression for covariance calculation within the document window

Examples

Calculate covariance in sales volume

Get population covariance between time and sales within company partition

Query:

db.stores.aggregate([{ $match: { "company": { $in: ["First Up Consultants"] } } }, { $setWindowFields: { "partitionBy": "$company", "sortBy": { "lastUpdated": 1 }, "output": { "covariancePopForSales": { "$covariancePop": [{ "$hour": "$lastUpdated" }, "$sales.totalSales"], "window": { "documents": ["unbounded", "current"] } } } } }, { $project: { "company": 1, "name": 1, "sales.totalSales": 1, "covariancePopForSales": 1 } }])

Output:

Documents with population covariance calculation between hour and total sales

Multi-field covariance analysis

Calculate covariance between different numerical fields

Query:

db.products.aggregate([{ $setWindowFields: { "partitionBy": "$category", "sortBy": { "price": 1 }, "output": { "priceQuantityCovariance": { "$covariancePop": ["$price", "$quantity"] } } } }])

Output:

Products with covariance between price and quantity fields

Related