{
$bucket: {
groupBy: ,
boundaries: [ , , ... ],
default: ,
output: {
: { <$accumulator expression> },
...
: { <$accumulator expression> }
}
}
}
groupBy:用于分组的字段
boundaries:基于groupBy分组的边界
default:不在边界之中的默认值
output:输出字段,除_id字段外,指定输出文档中要包含的字段的文档。要指定要包含的字段,必须使用累加器表达式($sum,$avg等)
新增文档:
db.bucket.insert([
{
"name": "雪碧1","price": 20,"year": 1982
},
{
"name": "雪碧2","price": 21,"year": 1983
},
{
"name": "雪碧3","price": 23,"year": 1984
}
,
{
"name": "雪碧4","price": 24,"year": 1985
},
{
"name": "雪碧6","price": 34,"year": 1990
},
{
"name": "雪碧7","price": 38,"year": 1992
},
{
"name": "雪碧8","price": 40,"year": 1972
},
{
"name": "雪碧7","price": 68,"year": 1998
}
])
根据价格分组划分区间并统计每个区间的数量
db.bucket.aggregate([{
$bucket:{
groupBy: "$price",
boundaries: [20,30,40,50],
default: "Other",
output:{
count: {
"$sum": 1
}
}
}
}])
{ $facet:
{
: [ , , ... ],
: [ , , ... ],
...
}
}
分面搜索,同一组输入文档上支持各种聚合,而不需要多次检索输入文档
根据价格和年份区间分组,分别统计每个区间的数量
db.bucket.aggregate( [
{
$facet: {
price: [{
$bucket:{
groupBy: "$price",
boundaries: [20,30,40,50],
default: "Other",
output:{
count: {
"$sum": 1
}
}
}
}],
year: [{
$bucket:{
groupBy: "$year",
boundaries: [1970,1980,1990,2000],
default: "Other",
output:{
count: {
"$sum": 1
}
}
}
}]
}
}
])