具有查找功能的 MongoDB 聚合

mongodb aggregate with find features

本文关键字:MongoDB 聚合 功能 查找      更新时间:2023-09-26

我有一个与此类似的模型:

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

我需要在我的视图中显示整个用户信息,但我还希望包括来自一个国家/地区的用户数量。

使用aggregate我不知道如何让完整用户通过我创建的组。

所以目前我正在做的是这样的:

User.find({}, function(err, users) {
  User.aggregate([
    { $group: { _id: { country: '$location.country' }, count: { $sum: 1 }}}
  ], function(err, results) {
    res.render('home', {
      users: users,
      countries: results
    });
  });
});

如您所见,我正在使用查找,然后聚合以获取我需要的信息......但我很确定有一种方法可以只使用 aggregate 来获取它,但我找不到如何做到这一点......

如果需要累积每个组的整个用户信息,则需要使用 $push 运算符进行累积,使用 $$ROOT 系统变量访问整个用户信息。

User.aggregate([
{$group:{"_id":{"country":"$location.country"},
         "users":{$push:"$$ROOT"},
         "count":{$sum:1}}}
],callback)

如果您只想累积用户信息文档的特定字段,您可以推送必填字段,例如:

User.aggregate([
{$group:{"_id":{"country":"$location.country"},
         "users":{$push:{"email":"$email","name":"$name"}},
         "count":{$sum:1}}}
],callback)