MongoDB 查询查找、求和和计数

MongoDB query find, sum and count

我的 collection 文档是区块链中的一个块,其中包含字段 {height, gasUsed, timestamp}

我想在特定的一天获得使用的总 gas(gasUsed 的总和)和总计数。

以下是我获取 2022 年 1 月 4 日内所有区块的查询

    db.getCollection('blocks').find({
        timestamp: {
            $gte: new Date(2022, 0, 4),
            $lt: new Date(2022, 0, 5)
        }
    }

我怎样才能同时获得 gasUsed 的总数和总和(2022 年 1 月 4 日内)?

您可以使用聚合框架 $match 和 $group 来实现:

db.collection.aggregate([
  {
    "$match": {
      "$and": [
        {
          "timestamp": {
            "$gte": new Date("2022-01-01")
          }
        },
        {
          "timestamp": {
            "$lt": new Date("2022-01-03")
          }
        }
      ]
    }
  },
  {
    "$group": {
      "_id": null,
      "total_count": { "$sum": 1 },
      "total_gas":   { "$sum": "$gasUsed" }
    }
  }
])

Working example