首页 > 解决方案 > Mongoose - 如何在数组中添加和返回值的总和

问题描述

这是我拥有的架构:

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

并且我使用(Post 是模型)检索多个文档:

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

我希望将每个文档中的 votes.votes 值总计为一个计数。如何做到这一点?

标签: javascriptnode.jsmongodbmongoosebackend

解决方案


如果您只想为该对象(即每个帖子)的数组总和,@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
                
            }) 

推荐阅读