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