湖北省建设厅网站查询,网页设计构建的基本流程,网站做法,宝应seo优化公司文章目录 语法使用举例在$group阶段中使用在$setWindowFields阶段使用 $count聚合运算符返回分组中文档的数量。从5.0开始支持。 语法
{ $count: { } }$count不需要参数
使用
$count可以用于下列聚合阶段#xff1a;
$bucket$bucket$group$setWindowFields
在$group阶段中… 文章目录 语法使用举例在$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和WAsortBy: { 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 }