MongoDB查询多个值

时间:2015-01-03 15:59:13

标签: javascript node.js mongodb mongoose

我的用户模型类似于:

{
  email: String,
  name: String,
  role: String,
  location: {
    country: String,
    city: String
  },
  contacts: {
    email: String,
    phone: String
  }
}

我的想法是在主页上显示以下信息:

  • 每个用户都有详细信息。
  • 每个国家/地区包含该用户数。
  • 该国家/地区中的每个城市都有该城市的用户数。

因此,在标题中我希望有一个国家/地区列表:

  • 英国(219)
  • 德国(128)
  • 法国(87)
  • 意大利(84)
  • 等...

每个国家/地区的城市列表:

  • 伦敦(119)
  • 利物浦(76)
  • 曼彻斯特(3)
  • 等...

在正文中,用户列表......

目前我的查询适用于除城市以外的所有内容。

查询是:

User.aggregate([
        { 
            $group: { 
                _id: { country: '$location.country' },
                users: { $push: '$$ROOT' },
                cities: { $addToSet: '$location.city' },
                count: { $sum: 1 }
            }
        }
    ], function(err, results) {

        console.log(results);

    });
};

$sum内加$addToSet会很高兴,但遗憾的是它不起作用。

如何改进此代码?

1 个答案:

答案 0 :(得分:0)

这是一个mongo查询,可以满足您的要求:

User.aggregate([
  { $group: { _id: { city: "$location.city", country: "$location.country" }, users: { $push: "$$ROOT" }, count: { $sum: 1 } } },
  { $group: { _id: "$_id.country", count: { $sum: "$count" }, cities: { $push: { city: "$_id.city", count: "$count", users: "$users" } } } }
], function(err, results) {
    console.log(results);
});