首页 > 解决方案 > 如何对同一集合中不同文档的值求和?

问题描述

I have photos with an array of likes. I am using mongoose as a db. I want to sum all the numeric values in the likes count of photo collection.
    exports.getAnalytics = (req, res) => {
  if (!req.user) {
    return res.redirect('/login');
  }
  Campaign.findOne({slug:req.params.slug}, (err, campaign) => {
    PhotoEntries.find({ CampaignId: campaign._id}, ['Photo','Name', 'done' ,'likes_count', ], {sort:{ _id: -1} }, function(err, photos) {
      
      PhotoEntries.countDocuments({CampaignId: campaign._id} , function (err, count) { 
          PhotoEntries.aggregate([
            {
              $group: {
                _id: "$CampaignId",
                Totallikes: { $sum: "$likes_count" }
              }
            }
          ]) 
    if(req.user){
      console.log(photos);
      res.render('admin/analytics', {
        title: 'Analytics',
        campaign: campaign,
        photolist : photos, 
        Count:count ,
        Totallikes: Totallikes  
        });
    }
  // }
  // ])

  });
  });
  });
  }   

但是它不起作用。错误是Arguments must be aggregate pipeline operators.我怎样才能做到这一点?
这是我的架构代码。var photoSchema = new Schema({ Name: {type: String}, Email: { type: String }, Photo: { type: String }, Description:{type:String}, PhoneNumber:{type:String}, CampaignId: {类型:Schema.Types.ObjectId,参考:'Campaigns',},

        done: {
          type: Boolean  ,
      },
    
      likes_count: Number ,default: 0,
        likedBy: [
          {
              type:Schema.Types.ObjectId,
              ref: "User"
          }
      ], 
      });
      }

我需要将该likes_count字段添加到集合中的所有文档中。

标签: mongodbexpressmongoose

解决方案


您错过了 input _id,按指定的_id表达式对输入文档进行分组,并且对于每个不同的分组,输出一个文档。每个输出文档的_id字段都包含唯一的按值分组。有关更多信息,请参阅$group

PhotoEntries.aggregate([
  {
    $group: {
      _id: null,
      Totallikes: { $sum: "$likes_count" }
    }
  }
])

操场


推荐阅读