如何对同一集合中不同文档的值求和? [英] How can I sum values from different documents in the same collection?
问题描述
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
});
}
// }
// ])
});
});
});
}
但是它不起作用.错误是参数必须是聚合管道运算符.
如何实现此目标?
这是我的架构代码.var photoSchema = new Schema({名称:{type:String},电子邮件:{类型:字符串},照片:{类型:字符串},说明:{type:String},电话号码:{type:String},CampaignId:{类型:Schema.Types.ObjectId,ref:广告系列",}
However it is not working. The error is Arguments must be aggregate pipeline operators.
How can I achieve this?
Here is my schema code.
var photoSchema = new Schema({
Name: {type: String},
Email: { type: String },
Photo: { type: String },
Description:{type:String},
PhoneNumber:{type:String},
CampaignId: {
type: Schema.Types.ObjectId,
ref: 'Campaigns',
},
done: {
type: Boolean ,
},
likes_count: Number ,default: 0,
likedBy: [
{
type:Schema.Types.ObjectId,
ref: "User"
}
],
});
}
我需要将 likes_count
字段添加到集合中的所有文档中.
I need to add the likes_count
field to all documents in the collection.
推荐答案
您错过了输入 _id
,按指定的 _id
表达式对输入文档进行分组,并针对每个不同的分组输出文档.每个输出文档的 _id
字段均包含唯一的按值分组.有关更多信息,请参见 $ group
You missed input _id
,
Groups input documents by the specified _id
expression and for each distinct grouping, outputs a document. The _id
field of each output document contains the unique group by value. For more information refer $group
PhotoEntries.aggregate([
{
$group: {
_id: null,
Totallikes: { $sum: "$likes_count" }
}
}
])
这篇关于如何对同一集合中不同文档的值求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!