MongoDB query find, sum and count
My document of a collection is a block in blockchain with fields {height, gasUsed, timestamp}
I want to get the total gas used (sum of gasUsed) and total count, given a particular day.
Below is my query to get all blocks within 4 Jan 2022
db.getCollection('blocks').find({
timestamp: {
$gte: new Date(2022, 0, 4),
$lt: new Date(2022, 0, 5)
}
}
How could I get the total count and sum of gasUsed as well (within 4 Jan 2022)?
Solution 1:
You can do it with Aggregation framework $match and $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