mongodb - mongodb加减一查询(减去两个查询结果)
问题描述
我有以下收藏:
[
{
"type": "debit",
"amount": 10
},
{
"type": "debit",
"amount": 20
},
{
"type": "credit",
"amount": 5
},
]
我需要将所有具有借方类型和减去贷方总和的文件相加。
我如何用 mongodb 处理这个问题?
所以我的预期结果是 25
解决方案
db.collection.aggregate([
{
"$group": {
"_id": "$type",
"field": {
$sum: {
"$cond": {
"if": {
"$eq": [
"$type",
"debit"
]
},
"then": "$amount",
"else": {
"$multiply": [
"$amount",
-1
]
}
}
}
}
}
},
{
"$group": {
"_id": null,
"result": {
"$sum": "$field"
}
}
}
])
推荐阅读
- typo3 - TYPO3:tx_news 分页和 CoolUri 的问题
- php - 如何在不使用 cURL 或 file_get_contents() 的情况下从 URL 读取数据
- ios - 如何使用泛型返回特定类型 NSManagedObject 的所有对象?
- c# - 使用 REGEX 将 RX123456789 替换为 RX*********
- aspnetboilerplate - 测试错误:无法加载文件或程序集'Castle.Core,版本 = 4.0.0.0,文化 = 中性
- php - 在谷歌地图上显示多张 api 结果照片
- http-post - 如何在 STRAPI 中发布关系
- python - AttributeError: 'NoneType' 对象在使用 pip 包安装包时没有属性'encoding'
- elasticsearch - 弹性搜索上的滚动时间增量效果
- javascript - 在 Selenium 中使用 Xpath 改变 innerHTML;Python 创建多个导致 SyntaxError: Invalid or unexpected token 的转义