文章目录
- 语法
- 使用
- 举例
- 在`$group`阶段中使用
- 在$setWindowFields阶段使用
$count
聚合运算符返回分组中文档的数量。从5.0开始支持。
语法
{ $count: { } }
$count
不需要参数
使用
$count
可以用于下列聚合阶段:
$bucket
$bucket
$group
$setWindowFields
在$group
阶段中使用{ $sum : 1 }
与$count
是等价的。
举例
使用下面的命令创建cakeSales
,它包含了在加利福尼亚California (CA)
和华盛顿Washington (WA)
的蛋糕销售记录:
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 }
] )
在$group
阶段中使用
下面的例子在$group
阶段中使用$count
统计在cakeSales
集合中每个州state
的蛋糕销售数量。
在本例中:
_id: "$state"
根据state
字段值对文档进行分组,分为CA
和WA
两个组$count: {}
:将分组内文档数据量设置给字段countNumberOfDocumentsForState
结果如下:
{ "_id" : "CA", "countNumberOfDocumentsForState" : 3 }
{ "_id" : "WA", "countNumberOfDocumentsForState" : 3 }
在$setWindowFields阶段使用
下面的例子在$setWindowFields
阶段使用$count
来统计cakeSales
集合所有window
中文档的数量:
db.cakeSales.aggregate( [
{
$setWindowFields: {
partitionBy: "$state",
sortBy: { orderDate: 1 },
output: {
countNumberOfDocumentsForState: {
$count: {},
window: {
documents: [ "unbounded", "current" ]
}
}
}
}
}
] )
在本例中:
partitionBy: "$state"
:根据state
对集合中的文档进行分区,分别为CA
和WA
sortBy: { orderDate: 1 }
根据orderDate
按照从小到大对分区中的文档进行排序,最早的orderDate
排在最前面- 将window中文档数量使用
$count
进行汇总后赋值给countNumberOfDocumentsForState
字段。
结果如下:
{ "_id" : 4, "type" : "strawberry", "orderDate" : ISODate("2019-05-18T16:09:01Z"),
"state" : "CA", "price" : 41, "quantity" : 162, "countNumberOfDocumentsForState" : 1 }
{ "_id" : 0, "type" : "chocolate", "orderDate" : ISODate("2020-05-18T14:10:30Z"),
"state" : "CA", "price" : 13, "quantity" : 120, "countNumberOfDocumentsForState" : 2 }
{ "_id" : 2, "type" : "vanilla", "orderDate" : ISODate("2021-01-11T06:31:15Z"),
"state" : "CA", "price" : 12, "quantity" : 145, "countNumberOfDocumentsForState" : 3 }
{ "_id" : 5, "type" : "strawberry", "orderDate" : ISODate("2019-01-08T06:12:03Z"),
"state" : "WA", "price" : 43, "quantity" : 134, "countNumberOfDocumentsForState" : 1 }
{ "_id" : 3, "type" : "vanilla", "orderDate" : ISODate("2020-02-08T13:13:23Z"),
"state" : "WA", "price" : 13, "quantity" : 104, "countNumberOfDocumentsForState" : 2 }
{ "_id" : 1, "type" : "chocolate", "orderDate" : ISODate("2021-03-20T11:30:05Z"),
"state" : "WA", "price" : 14, "quantity" : 140, "countNumberOfDocumentsForState" : 3 }