javascript - 在 Mongo 视图中求和和输出总计
问题描述
在我的 mongDB 后端,我有一个视图,在多个聚合阶段之后,输出如下所示的信息:
{
"_id" : 25k3ejfjyi32132f9z3,
"customer_id" : 15cgrd582950jj493g5,
"openBalance": 24,
// other data...
},
{
"_id" : 35g6ejfjfj32132f8s4,
"customer_id" : 23gtrd684563jj494f4
"openBalance": 20,
// other data...
}
作为最后一步,我需要做的是汇总所有记录的所有“openBalance”金额,并将该数字与其他数据一起输出到新字段中。所以,换句话说,根据上面的数据,我想44
在一个名为totalOpenBalance
.
有没有办法可以在 mongo 视图中处理这个聚合逻辑?我不知道该怎么做,因为我不想为返回的每条记录添加一个字段,而是根据记录的总数返回一个值?它看起来像这样:
{
"_id" : 25k3ejfjyi32132f9z3,
"customer_id" : 15cgrd582950jj493g5,
"openBalance": 24,
// other data...
},
{
"_id" : 35g6ejfjfj32132f8s4,
"customer_id" : 23gtrd684563jj494f4
"openBalance": 20,
// other data...
},
"totalOpenBalance": 44
解决方案
如果将以下代码添加到管道的末尾
$group: {
_id: null, // do not really group but throw all documents into the same bucket
documents: { $push: "$$ROOT" }, // push each encountered document into the group
totalOpenBalance: { $sum: "$openBalance" } // sum up all "openBalance" values
}
你会得到一些你可以使用的东西:
{
"_id" : null,
"documents" : [
{
"_id" : 25k3ejfjyi32132f9z3,
"customer_id" : 15cgrd582950jj493g5,
"openBalance" : 24
},
{
"_id" : 35g6ejfjfj32132f8s4,
"customer_id" : 23gtrd684563jj494f4,
"openBalance" : 20
}
],
"totalOpenBalance" : 44
}
如果您想完全发疯,我不建议您继续阅读。通过添加以下阶段
{
$group: {
_id: null, // do not really group but throw all documents into the same bucket
documents: { $push: "$$ROOT" }, // push each encountered document into the group
totalOpenBalance: { $sum: "$openBalance" } // sum up all "openBalance" values
}
}, {
$project: {
"_id": 0, // remove the "_id" field
"documents": { $concatArrays: [ "$documents", [ { "totalOpenBalance": "$totalOpenBalance" } ] ] } // append a magic subdocument to the the existing documents
}
}, {
$unwind: "$documents" // just so we can flatten the resulting array into separate documents
}, {
$replaceRoot: {
newRoot: "$documents" // and move the content of our documents field to the root
}
}
你得到的正是你所要求的:
{
"_id" : 25k3ejfjyi32132f9z3,
"customer_id" : 15cgrd582950jj493g5,
"openBalance" : 24
},
{
"_id" : 35g6ejfjfj32132f8s4,
"customer_id" : 23gtrd684563jj494f4,
"openBalance" : 20
},
{
"totalOpenBalance" : 44
}
然而,这可能只是矫枉过正......
推荐阅读
- c++ - 如何解决分段错误单链表?
- r - 将命名向量传递到 str_replace_all 以替换多个模式
- typescript - 无法窥探原始值;给定的未定义
- caching - Cloudflare 按前缀清除缓存不起作用
- css - 脉轮卡组件是垂直映射而不是水平映射
- spring - 用于在反序列化期间忽略未知属性的 SpringMVC 全局设置
- javascript - Angular 不更新 *ngFor 循环
- python - 如何绘制具有多个数据集的多个分类器的准确性
- python - 由于日期时间比较,根据时间框架中断过滤 icalendar 事件
- python - 用于从新的 www.ffiec.gov 站点抓取银行控股公司 (FR Y-9C) 数据的 Curl 命令(或无头 python 替代方案)?