首页 > 解决方案 > 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 ] } }}

   ]
)

请帮我解决这个问题。

标签: mongodbaggregation-framework

解决方案


您必须查看$unwind运算符,它解构数组以为数组的每个元素输出一个文档。还要看看addproject运算符。

我假设您的数据库查询应如下所示:

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

推荐阅读