$covarianceSamp(聚合)
定义
新版本5.0.
返回使用$setWindowFields阶段中的文档评估的两个数值表达式的样本协方差。表达式在$setWindowFields$setWindowFields阶段窗口中评估。
$covarianceSamp仅在$setWindowFields阶段可用。
{ $covarianceSamp: [ <numeric expression 1>, <numeric expression 2> ] }
行为
忽略窗口中的非数值、
null值和缺失字段。如果窗口包含一个文档,则返回
null。(与返回0的$covariancePop不同,如果窗口包含一个文档。)如果窗口为空,则返回
null。如果窗口包含
NaN值,则返回NaN。如果窗口包含一个或多个所有都是正数或所有都是负数的
Infinity值,则返回Infinity。返回的Infinity值与窗口中的Infinity值的符号相同。如果窗口包含具有不同符号的
Infinity值,则返回NaN。如果窗口包含
decimal值,则返回decimal值。如果上述任何一点都不适用,则返回一个
double值。
返回值的优先级顺序如下
NaNInfinitydecimaldouble
示例
创建一个包含加利福尼亚州(CA)和华盛顿州(WA)糕点销售的cakeSales集合
db.cakeSales.insertMany( [ { _id: 0, type: "chocolate", orderDate: new Date("2020-05-18T14:10:30Z"), state: "CA", price: 13, quantity: 120 }, { _id: 1, type: "chocolate", orderDate: new Date("2021-03-20T11:30:05Z"), state: "WA", price: 14, quantity: 140 }, { _id: 2, type: "vanilla", orderDate: new Date("2021-01-11T06:31:15Z"), state: "CA", price: 12, quantity: 145 }, { _id: 3, type: "vanilla", orderDate: new Date("2020-02-08T13:13:23Z"), state: "WA", price: 13, quantity: 104 }, { _id: 4, type: "strawberry", orderDate: new Date("2019-05-18T16:09:01Z"), state: "CA", price: 41, quantity: 162 }, { _id: 5, type: "strawberry", orderDate: new Date("2019-01-08T06:12:03Z"), state: "WA", price: 43, quantity: 134 } ] )
本例使用$covarianceSamp在$setWindowFields阶段中输出糕点销售的orderDate年份和quantity值的相关样本协方差
db.cakeSales.aggregate( [ { $setWindowFields: { partitionBy: "$state", sortBy: { orderDate: 1 }, output: { covarianceSampForState: { $covarianceSamp: [ { $year: "$orderDate" }, "$quantity" ], window: { documents: [ "unbounded", "current" ] } } } } } ] )
在示例中
partitionBy: "$state"根据state对集合中的文档进行分区。存在CA和WA的分区。sortBy: { orderDate: 1 }按升序(1)对每个分区中的文档进行排序,以便最早的orderDate排在第一位。
output使用在documents窗口中运行的$covarianceSamp来设置orderDate年份和quantity值的样本协方差。window包含在输出中位于无界下限和当前文档之间的文档。这意味着$covarianceSamp将covarianceSampForState字段设置为从分区开始到当前文档之间的文档的相关样本协方差。
在此输出中,相关样本协方差显示在covarianceSampForState字段中
{ "_id" : 4, "type" : "strawberry", "orderDate" : ISODate("2019-05-18T16:09:01Z"), "state" : "CA", "price" : 41, "quantity" : 162, "covarianceSampForState" : null } { "_id" : 0, "type" : "chocolate", "orderDate" : ISODate("2020-05-18T14:10:30Z"), "state" : "CA", "price" : 13, "quantity" : 120, "covarianceSampForState" : -21 } { "_id" : 2, "type" : "vanilla", "orderDate" : ISODate("2021-01-11T06:31:15Z"), "state" : "CA", "price" : 12, "quantity" : 145, "covarianceSampForState" : -8.500000000000007 } { "_id" : 5, "type" : "strawberry", "orderDate" : ISODate("2019-01-08T06:12:03Z"), "state" : "WA", "price" : 43, "quantity" : 134, "covarianceSampForState" : null } { "_id" : 3, "type" : "vanilla", "orderDate" : ISODate("2020-02-08T13:13:23Z"), "state" : "WA", "price" : 13, "quantity" : 104, "covarianceSampForState" : -15 } { "_id" : 1, "type" : "chocolate", "orderDate" : ISODate("2021-03-20T11:30:05Z"), "state" : "WA", "price" : 14, "quantity" : 140, "covarianceSampForState" : 3 }