Ho 对对象数组使用 $sum(聚合)并检查大于每个总和

Ho use $sum (aggregation) for array of object and check greater than for each sum

我的文档结构如下:

{
    "_id" : ObjectId("621ccb5ea46a9e41768e0ba8"),
    "cust_name" : "Anuj Kumar",
    "product" : [
        {
            "prod_name" : "Robot",
            "price" : 15000
        },
        {
            "prod_name" : "Keyboard",
            "price" : 65000
        }
    ],
    "order_date" : ISODate("2022-02-22T00:00:00Z"),
    "status" : "processed",
    "invoice" : {
        "invoice_no" : 111,
        "invoice_date" : ISODate("2022-02-22T00:00:00Z")
    }
}

如何进行以下查询... 列出价值>10000的订单详情。

我只想显示价格总和大于 10000 的对象

我试试这个

db.order.aggregate([{$project : {sumOfPrice : {$sum : "$product.price"} }}])

输出

{ "_id" : ObjectId("621ccb5ea46a9e41768e0ba8"), "sumOfPrice" : 80000 }
{ "_id" : ObjectId("621ccba9a46a9e41768e0ba9"), "sumOfPrice" : 16500 }
{ "_id" : ObjectId("621ccbfaa46a9e41768e0baa"), "sumOfPrice" : 5000 }

我想检查这个 sumOfPrice 是否大于 10000 并显示那些订单完整对象。

您可以在检查此条件后立即添加一个 $match 阶段,如下所示:

db.collection.aggregate([
  {
    $addFields: {
      sumOfPrice: {
        $sum: "$product.price"
      }
    }
  },
  {
    $match: {
      sumOfPrice: {
        $gt: 10000
      }
    }
  }
])

Mongo Playground

您还可以将 $expr 运算符与查找查询一起使用:

db.order.find({
    $expr: {
        $gt: [ {$sum: '$product.price'}, 10000 ]
    }
})

Mongo Playground