mongodb - 如何对同一集合中不同文档的值求和?
问题描述
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
字段添加到集合中的所有文档中。
解决方案
推荐阅读
- graph-theory - 在 SSC 中搜索特定节点时,DFS 是否比 BFS 快?
- routing - 在 Angular 6 中,我如何访问 app.component.ts 中的路由值
- php - PHP中的最终抽象类?
- r - R包从静态图像中猜测xy坐标?
- java - 如何处理带有最终字段的空构造函数
- c# - 需要一种方法来卸载先前选择的 TabPage 以释放 USER 对象
- go - 如何删除golang切片之间的重复元素
- d3.js - 我正在尽最大努力让 D3 Hierachy 树运行。但未能追加
- javascript - How can I refactor my 'view' code to display items per year?
- python - 为什么即使遇到`RuntimeError`,asyncio 事件循环有时也能完成任务?