MongoDB 聚合:数组数据中字段的总和以及父集合中的项目

MongoDB aggregation: sum of a field inside an array data and project that on parent collection

我有两个收款,一个是发票,一个是付款

发票集合如下所示

{
  _id: "123",
  client: "ABC"
}

收款看起来像

{
  _id: "456",
  invoiceId: "123",
  amount: 100
},
{
  _id: "789",
  invoiceId: "123",
  amount: 50
}

我想要这样的输出

{
  _id: "123",
  client: "ABC",
  amount: 150
}

您可以使用 $lookup$project$sum 实现它,如下所示:

db.invoice.aggregate([
    {
        //you can remove this stage if you don't need to filter your data
        "$match": {
            "_id": "123"
        }
    },
    {
        "$lookup": {
            "from": "payment",
            "as": "payments",
            "localField": "_id",
            "foreignField": "invoiceId"
        }
    },
    {
        "$project": {
            "client": 1,
            "amount": {
                "$sum": "$payments.amount"
            }
        }
    }
])

您可以使用以下聚合,这样您就不需要手动投影项目:

db.invoices.aggregate([
  {
    $lookup: {
      from: "payments",
      localField: "_id",
      foreignField: "invoiceId",
      as: "payments"
    }
  },
  {
    $addFields: {
      amount: {
        $sum: "$payments.amount"
      }
    }
  },
  {
    $project: {
      payments: 0
    }
  }
])

Mongoplayground