$covarianceSamp
Calculates the sample covariance of two numerical expressions within a specified document window, providing unbiased covariance estimate for statistical analysis.
Syntax
{ $covarianceSamp: [<numericalExpression1>, <numericalExpression2>] }
Parameters
numericalExpression1
objectrequiredFirst numerical expression for sample covariance calculation within the document window
numericalExpression2
objectrequiredSecond numerical expression for sample covariance calculation within the document window
Examples
Calculate sample covariance between unbounded and current document
Compute sample covariance for stores partitioned by company with date sorting
Query:
db.stores.aggregate([{ $match: { "company": { $in: ["First Up Consultants"] }, "$and": [{ "storeOpeningDate": { "$gt": ISODate("2024-09-01T03:06:24.180Z") } }, { "storeOpeningDate": { "$lt": ISODate("2025-09-30T03:55:17.557Z") } }] } }, { $setWindowFields: { "partitionBy": "$company", "sortBy": { "storeOpeningDate": 1 }, "output": { "covarianceSampForSales": { "$covarianceSamp": [{ "$hour": "$storeOpeningDate" }, "$sales.revenue"], "window": { "documents": ["unbounded", "current"] } } } } }])
Output:
Documents with sample covariance between opening hour and sales revenue
Revenue and cost covariance
Calculate sample covariance between revenue and cost metrics
Query:
db.financial.aggregate([{ $setWindowFields: { "partitionBy": "$department", "sortBy": { "month": 1 }, "output": { "revenueCostCovariance": { "$covarianceSamp": ["$revenue", "$cost"] } } } }])
Output:
Financial documents with sample covariance between revenue and cost