javascript - 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 值总计为一个计数。如何做到这一点?
解决方案
如果您只想为该对象(即每个帖子)的数组总和,@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
})
推荐阅读
- solr - 在 Hybris 中过滤 Solr 自动建议
- python - 使用 python 创建模型时处理 NAN 值
- excel - VBA 搜索值并从列表中删除(for 循环太慢)
- quill - Quill 自定义印迹:如何使 Quill 接受“传入”自定义代码
- node.js - Terser 丑化了 Node.js 环境中的 process.env,使其无法使用
- rest - 在rest api body中定义“外键”元素时的命名约定
- java - 字符串索引超出范围:0 在 Spring Boot 中使用 RedirectAttributes 时出错
- formatting - 更改 PyCharm 中 Black 插件的 88 个字符限制
- javascript - 在动态创建的 AJAX 元素上使用 $(window) 进行事件绑定
- http - HTTP Chrome 请求中的 CRLF