MongoDB – Mongoose:聚合生成,$ match $ group $项目

我是mongoDB世界的新手。 我正在用js和mongoose作为DB在nodeJS上开发一个网站。

我正在学习graphics方向,我用这个模型生成一个数据库:

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') } }); 

在不同的页面上,我想要显示一些统计信息,例如用户select光照或黑暗的页面亮度。 我想向他展示大多数人select的东西。

例如,与性别:大多数select女性(例如,其中68%select光)。 我认为让所有数字创build统计数据的最好方法是使用聚合。

作为新手,它破坏了我的想法,以产生完美的查询,我真的迷失在这个框架!

会爱你的build议!

您的聚合操作将取决于$grouppipe道步骤中的$cond操作符,以基于页面光度和/或页面颜色来计算计数。 使用$sum accumulator操作符返回每个评估组的总和,如下所示:

 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); })