【问题标题】:Mongoose ADDING/SUMING subdocument array value which is within another subdocument arrayMongoose ADDING/SUMING 子文档数组值,它位于另一个子文档数组中
【发布时间】:2020-09-17 14:44:30
【问题描述】:

我的文档如下所示:

_id:'111'
products:[
   {
    _id:'pqr'
    nums:[
      {_id:'aaa',
      quantity:30
      },
      {_id:'bbb',
       quantity:40
      }
    ]
   }
]

我需要得到:

(i) nums 子文档中的数量字段的总和,该子文档又在 products 子文档中。

(ii) 要作为一个整体返回的 products 数组(其中包含计算的数量和 nums 子文档)

以下是我希望输出的样子:

products:[
  {
   _id: 'pqr',
   nums:[
      {_id:'aaa',
      quantity:30
      },
      {_id:'bbb',
       quantity:40
      }
   ],
   quantity: 70
  }
]

到目前为止,我已经尝试过这样做

    Shop.aggregate([

         {$match: {'_id':'111'},

         {$unwind: "$products"},

         {$group:{
            _id : "$_id",
            nums:{$last:"$nums"},
            quatity: //I have no idea how to get this total quantity which corresponds to _id:'pqr'
          }
         }

    ])

关于如何做到这一点的任何解决方法?

【问题讨论】:

    标签: mongodb mongoose aggregation-framework


    【解决方案1】:

    这是$reduce 的一个很好的用例:

    Shop.aggregate([
         {$match: {'_id':'111'},
         {$unwind: "$products"},
         {$addFields:{
              "products.quantity":{
                  $reduce:{
                       input: "$products.nums",
                       initialValue: 0
                       in: {$sum:["$$value","$$this.quantity"]}
                  }
              }
          }}
    ])
    

    【讨论】:

      猜你喜欢
      • 2017-09-17
      • 2018-01-26
      • 2016-12-14
      • 1970-01-01
      • 2019-06-03
      • 2017-03-21
      • 2017-06-06
      • 2015-12-22
      相关资源
      最近更新 更多