查询mongo对象-聚合

时间:2020-02-22 04:59:47

标签: mongodb nested aggregation

我有一个像这样的json:

[
  {
    "Customer_ID": 1,
    "Order": [
      {
        "Item": "A",
        "Price": 2,
        "Quantity": 6
      },
      {
        "Item": "B",
        "Price": 3,
        "Quantity": 6
      },
      {
        "Item": "C",
        "Price": 2,
        "Quantity": 8
      }
    ]
  }
]

我想要这样的结果:

总价是价格和数量的乘积

客户,总价

1,46

2,..

3,..

有人可以帮我进行mongo查询吗?

1 个答案:

答案 0 :(得分:0)

我希望这会对您有所帮助,

[{
    $project: {
        customer: '$Customer_ID',
        values: {
            $map: {
               input: '$Order',
               as: 'item',
               'in': { $multiply: [ '$$item.Price', '$$item.Quantity' ]}
            }
        }
    }
 }, 
 {
     $project: {
         customer:'$customer',
         totalValue: {
             $sum: '$values'
         }
     }
 }]

让我解释一下这里发生了什么,在第一个 $ project 块中,我们将 Customer_ID 投影为 customer ,并将每个订单价格数量作为。然后在下一个 $ project 块中,将所有项目添加到 values 数组中,并投影为 totalValue