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运算符,该运算符对数组进行解构以为数组的每个元素输出文档。还可以看一下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
])

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章