我是mongoDB世界的新手。我正在nodeJS上开发一个expressJS和猫鼬数据库的网站。
我正在学习图形定向,我用这个模型生成了一个DB:
var userSchema = new Schema({
profile:{
sexe: String, // ('male' or 'female')
age: String, // ('kid', 'adult', 'old')
rank: String, // ('low', 'middle', 'high')
},
design:{
luminosity: String, // ('light', 'dark')
color: String, // ('blue', 'green', 'pink', 'orange')
shape: String, // ('rounded', 'squared')
font: String, // ('serif', 'sans serif')
}
});在不同的页面上,我想显示一些统计数据,例如,在页面亮度上,用户选择光还是暗。我想向他展示人们最喜欢的东西。
例如,在“性别”一节中,主要挑选女性的是什么(例如,68%的女性选择光)。我认为获取所有数字来创建统计数据的最好方法是使用聚合。
作为新手,它摧毁了我的头脑产生完美的查询,我真的迷失在这个框架中!
会喜欢你的建议的!
发布于 2015-11-12 11:20:28
聚合操作将依赖于$cond管道步骤中的$group操作符来根据页面亮度和/或页面颜色评估计数。使用$sum累加器操作符返回每个评估组的和,如下所示:
var pipeline = [
{
"$group": {
"_id": "$profile.sexe",
"light_count": {
"$sum": {
"$cond": [ { "$eq": [ "$design.luminosity", "light" ] }, 1, 0 ]
}
},
"dark_count": {
"$sum": {
"$cond": [ { "$eq": [ "$design.luminosity", "dark" ] }, 1, 0 ]
}
},
"blue_count": {
"$sum": {
"$cond": [ { "$eq": [ "$design.color", "blue" ] }, 1, 0 ]
}
},
"green_count": {
"$sum": {
"$cond": [ { "$eq": [ "$design.color", "green" ] }, 1, 0 ]
}
},
"pink_count": {
"$sum": {
"$cond": [ { "$eq": [ "$design.color", "pink" ] }, 1, 0 ]
}
},
"orange_count": {
"$sum": {
"$cond": [ { "$eq": [ "$design.color", "orange" ] }, 1, 0 ]
}
}
}
},
{
"$project": {
"_id": 0, "gender": "$_id",
"luminosity": {
"light": "$light_count",
"dark": "$dark_count"
},
"color": {
"blue": "$blue_count",
"green": "$green_count",
"pink": "$pink_count",
"orange": "$orange_count"
}
}
}
];
User.aggregate(pipeline)
.exec(function (err, result){
// handle error
if (err) throw Error;
console.log(result);
})https://stackoverflow.com/questions/33669735
复制相似问题