简体   繁体   English

ZCCADCDEDB567ABAE643E15DCF0974E503Z - 如何在数组中添加和返回值的总和

[英]Mongoose - How to add and return a sum of values in an array

This is the schema that I have:这是我拥有的架构:

let postScheme = new Schema({
    title: {
        type: String,
        required: true
    },
    body: String,
    isImage: Boolean,
    imageUrl: String,
    icon: String,
    time: {
        type: String,
        required: true
    },
    username: {
        type: String,
        required: true
    },
    votes: [{tag: String, votes: Number}], //array of {tag, votes}
    usersVoted: Array,
    tags: Array, //array of tags
})

and Im retrieving multiple documents using (Post is the model):并且我使用(Post 是模型)检索多个文档:

Post.find({username: 'example'})

I want the votes.votes value from each document to be totaled into one count.我希望将每个文档中的 votes.votes 值总计为一个计数。 How can this be achieved?如何做到这一点?

You can use $sum opeator:您可以使用$sum运算符:

let result = Post.aggregate([
    { $match: {username: 'example'} },
    { $addFields: { totalCount: { $sum: "$votes.votes" } } }
])

The method @mickl has mentioned works well if you would like the sum of the array for that object only (ie, for each post).如果您只想为该 object (即每个帖子)的数组求和,@mickl 提到的方法效果很好。 Pointing that out if that helps anyone.指出这是否对任何人有帮助。

I was looking to have all the values summed into one single variable, and unwinding it has made it possible as shown here:我希望将所有值汇总到一个变量中,然后展开它使其成为可能,如下所示:

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
                
            }) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM