如何解决猫鼬-如何在数组中添加和返回值的总和
这是我拥有的架构:
let postScheme = new Schema({
title: {
type: String,required: true
},body: String,isImage: Boolean,imageUrl: String,icon: String,time: {
type: String,username: {
type: String,votes: [{tag: String,votes: Number}],//array of {tag,votes}
usersVoted: Array,tags: Array,//array of tags
})
并且我使用(Post是模型)检索多个文档:
Post.find({username: 'example'})
我希望将每个文档的votes.votes值总计为一个计数。如何实现?
解决方法
您可以使用$sum运算符:
let result = Post.aggregate([
{ $match: {username: 'example'} },{ $addFields: { totalCount: { $sum: "$votes.votes" } } }
])
,
如果您只希望该对象(即每个帖子)的数组总和,@ mickl提到的方法就很好用。指出是否有帮助。
我一直希望将所有值加到一个变量中,并且展开它使得如下所示成为可能:
Post.aggregate([
{ $match: { username: 'example' } },{ $unwind: {path: '$votes'}},{ $group: {_id: null,totalVotes: {$sum: '$votes.votes'}}}
])
.exec((err,result) => {
if (err) {
//err stuff
}
let totalVotes = result[0].totalVotes //The sum of all the votes.votes
})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。