MongoDB query find, sum and count



我的集合文档是区块链中的一个块,字段为{height,gasUsed,timestamp}

我想得到特定日期的总用气量(用气量的总和(和总计数。

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

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

我如何才能获得所用气体的总数和总和(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" }
}
}
])

工作示例

最新更新