首先bucket按年龄而boundaries
为[0,20,30,40,50,200]
db.user.aggregate(
{$project: {_id:0, age:{$subtract:[{$year:new Date()}, {$year:"$birthDay"}]} } },
{$bucket:{
groupBy:"$age",
boundaries:[0,20,30,40,50,200]
}},
{ $project:{ _id:0,age:"$_id",count:1 } }
)
得到以下结果
{ "count" : 5, "age" : 20 }
{ "count" : 1, "age" : 30 }
然后我想进一步统计每个城市的每个年龄段数
{ city : "SH", age: 20, count: 2 }
{ city : "BJ", age: 20, count: 3 }
{ city : "BJ", age: 30, count: 1 }
那么在这种情况下如何实现呢?
另外
db.user.aggregate(
{ $project: {_id:0, city:1, age:{$subtract:[{$year:new Date()}, {$year:"$birthDay"}]} } },
{ $group: { _id:"$city",ages:{$push:"$age"} } },
{ $project: {_id:0, city:"$_id",ages:1} }
)
{ "city" : "SH", "ages" : [ 26, 26 ] }
{ "city" : "BJ", "ages" : [ 27, 26, 26, 36 ] }
答案 0 :(得分:5)
您所谈论的内容实际上是使用$switch
在常规$group
阶段实施的:
db.user.aggregate([
{ "$group": {
"_id": {
"city": "$city",
"age": {
"$let": {
"vars": {
"age": { "$subtract" :[{ "$year": new Date() },{ "$year": "$birthDay" }] }
},
"in": {
"$switch": {
"branches": [
{ "case": { "$lt": [ "$$age", 20 ] }, "then": 0 },
{ "case": { "$lt": [ "$$age", 30 ] }, "then": 20 },
{ "case": { "$lt": [ "$$age", 40 ] }, "then": 30 },
{ "case": { "$lt": [ "$$age", 50 ] }, "then": 40 },
{ "case": { "$lt": [ "$$age", 200 ] }, "then": 50 }
]
}
}
}
}
},
"count": { "$sum": 1 }
}}
])
结果:
{ "_id" : { "city" : "BJ", "age" : 30 }, "count" : 1 }
{ "_id" : { "city" : "BJ", "age" : 20 }, "count" : 3 }
{ "_id" : { "city" : "SH", "age" : 20 }, "count" : 2 }
$bucket
管道阶段只占用一个字段路径。您可以通过"output"
选项拥有多个累加器,但"groupBy"
是一个表达式。
请注意,您也可以在此处使用$let
,而不是单独的$project
管道阶段来计算" age"。
N.B如果您实际向$bucket
抛出一些错误的表达式,您将收到有关$switch
的错误,这应该暗示您这是在内部实现的方式。
如果您担心$switch
中的编码,那么只需生成它:
var ranges = [0,20,30,40,50,200];
var branches = [];
for ( var i=1; i < ranges.length; i++) {
branches.push({ "case": { "$lt": [ "$$age", ranges[i] ] }, "then": ranges[i-1] });
}
db.user.aggregate([
{ "$group": {
"_id": {
"city": "$city",
"age": {
"$let": {
"vars": {
"age": {
"$subtract": [{ "$year": new Date() },{ "$year": "$birthDay" }]
}
},
"in": {
"$switch": { "branches": branches }
}
}
}
},
"count": { "$sum": 1 }
}}
])
答案 1 :(得分:0)
db.user.mapReduce(
function(){
var age = new Date().getFullYear() - this.birthDay.getFullYear();
var ages = [0,20,30,40,50,200]
for(var i=1; i<ages.length; i++){
if(age < ages[i]){
emit({city:this.city,age:ages[i-1]},1);
break;
}
}
},
function(key, counts){
return Array.sum(counts);
},
{ out: "user_city_age_count" }
)