mongo聚合查詢之 $bucket的作用:
大致說明:分段統計表的數據
```
{
$bucket: {
groupBy: <expression>, // 需要統計的信息 可以是表達式或者字段
boundaries: [ <lowerbound1>, <lowerbound2>, ... ], // 約束信息的范圍
default: <literal>, // 不在約束范圍內的默認值
output: { //輸出的字段信息
<output1>: { <$accumulator expression> },
...
<outputN>: { <$accumulator expression> }
}
}
}
```
數據
~~~
{ "_id" : 1, "title" : "title1", "year" : 1926,
"price" : NumberDecimal("199.99") }
{ "_id" : 2, "title" : "title2", "year" : 1902,
"price" : NumberDecimal("280.00") }
{ "_id" : 3, "title" : "title3", "year" : 1925,
"price" : NumberDecimal("76.04") }
{ "_id" : 4, "title" : "title4",
"price" : NumberDecimal("167.30") }
{ "_id" : 5, "title" : "title5
"price" : NumberDecimal("483.00") }
{ "_id" : 6, "title" : "title6" : 1913,
"price" : NumberDecimal("385.00") }
{ "_id" : 7, "title" : "title7", "year" : 1893}
{ "_id" : 8, "title" : "title8", "year" : 1918,
"price" : NumberDecimal("118.42") }
~~~
執行查詢:
~~~
db.artwork.aggregate( [
{
$bucket: {
groupBy: "$price", // 對prices字段進行統計查詢
boundaries: [ 0, 200, 400 ], // 數據的邊界范圍,包左不包右
default: "Other", // 不在boundaries內的默認名稱
output: {
"count": { $sum: 1 }, // 統計
"titles" : { $push: "$title" } // 將改范圍內的title組成數組
}
}
}
] )
~~~
結果:
~~~
{
"_id" : 0,
"count" : 4,
"titles" : ["title1","title3","title4","title8"]
}// 0<=prices<200
{
"_id" : 200,
"count" : 2,
"titles" : [
"title2",
"title6"
]
}// 200<=prices<400
{
"_id" : "Other",
"count" : 2,
"titles" : [
"title5",
"title7"
]
}// 不在0-400范圍內的
~~~