You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MongoDB中计算指定日期的交易总金额

计算指定日期的MongoDB交易总金额

现有MongoDB文档

[
  {
    "_id": {
      "$oid": "64a5a396ec152ab4f5e1c60c"
    },
    "firstName": "Ram",
    "lastName": "Shayam",
    "email": "abc@123.com",
    "transactions": [
      {
        "amount": 22,
        "date": "21/7"
      },
      {
        "amount": 12,
        "date": "21/7"
      },
      {
        "amount": 50,
        "date": "19/7"
      },
      {
        "amount": 100,
        "date": "19/7"
      }
    ]
  }
]

已执行的筛选聚合操作

此前已通过以下聚合操作筛选出日期为"21/7"的交易列表:

db.collection.aggregate([
  {
    $match: {
      firstName: "Ram"
    }
  },
  {
    $unwind: "$transactions"
  },
  {
    $match: {
      "transactions.date": {
        $eq: "21/7"
      }
    }
  },
  {
    $group: {
      _id: "$_id",
      list: {
        $push: "$transactions"
      }
    }
  }
])

筛选结果

[
  {
    "_id": ObjectId("64a5a396ec152ab4f5e1c60c"),
    "list": [
      {
        "amount": 22,
        "date": "21/7"
      },
      {
        "amount": 12,
        "date": "21/7"
      }
    ]
  }
]

需求:计算指定日期交易总金额

需要修改聚合操作,计算"21/7"日期的交易总金额,期望结果为34。

解决方案:修改后的聚合操作

在筛选出目标交易后,使用$sum操作符累加金额:

db.collection.aggregate([
  {
    $match: {
      firstName: "Ram"
    }
  },
  {
    $unwind: "$transactions"
  },
  {
    $match: {
      "transactions.date": "21/7"
    }
  },
  {
    $group: {
      _id: "$_id",
      totalAmount: {
        $sum: "$transactions.amount"
      }
    }
  }
])

执行结果

[
  {
    "_id": ObjectId("64a5a396ec152ab4f5e1c60c"),
    "totalAmount": 34
  }
]

内容的提问来源于stack exchange,提问作者Geekyvinayak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 05:16:31