mongodb - MongoDb 使用 $add 聚合嵌套文档
问题描述
我需要从嵌套文档中获取总和值。
数据库文件:
{
"_id": 123,
"products": [
{
"productId": 1,
"charges": [
{
"type": "che",
"amount": 100
}
]
}
]
}
我想得到总和值。
在sumValue = products.charges.amount+20;
哪里和"products.productId"
是1
"products.charges.type"
"che"
我尝试了以下查询,但没有希望:
db.getCollection('test').aggregate(
[
{"$match":{$and:[{"products.productId": 14117426}, {"products.charges.type":"che"}]},
{ $project: { "_id":0, total: { $add: [ "$products.charges.price", 20 ] } }}
]
)
请帮我解决这个问题。
解决方案
您必须查看$unwind运算符,它解构数组以为数组的每个元素输出一个文档。还要看看add和project运算符。
我假设您的数据库查询应如下所示:
db.test.aggregate([
{$unwind: '$products'}, // Unwind products array
{$match: {'products.productId' : 3}}, // Matching product id
{$unwind: '$products.charges'}, // Unwind charges
{$match: {'products.charges.type' : 'che'}}, // Matching charge type of che
{$project: {'with20': {$add: ["$products.charges.amount", 20]}}}, // project total field which is value + 20
{$group: {_id : null, amount: { $sum: '$with20' }}} // total sum
])
推荐阅读
- python - Python for 循环仅返回字典的最后一个值
- mysql - 更改 my.ini 后无法启动 MySQL 服务
- apache-kafka - JBPM:当Kafka Topic中有消息时触发业务流程
- google-colaboratory - 如何在不影响互联网中断的情况下在 Colab 中训练模型?
- python - 具有距离阈值停止准则的编辑距离矩阵的单链接聚类
- dart - 如何设置文本字段宽度?
- go - 为什么我在下面的 golang 代码示例中使用 defer 得到 0 和 1
- android - 如何使用 Kotlin 和 Moshi 在 Android 中将 JSON 2019-04-28T00:00:00 格式转换为 GregorianCalender
- ibm-cloud - IBM Cloud Dedicated 是在企业网络中部署我们的应用程序的正确解决方案吗?
- sql - 如何在函数中使用 SELECT 来比较字段