文章目錄
- 語法
- 使用
- 舉例
- 在`$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 }