2

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)?

1
  • 1
    Can you add an example of your collection and expected output? Commented Jan 11, 2022 at 15:51

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

6 Comments

The answer is almost perfect except there is one excess } in the last 4th line. Unfortunately, I failed to update it. Please correct it if you can.
I learned something useful from your answer. We can use Date("YYYY-MM-DD") to specify the date in a more readable way, instead of Date(YYYY,M-1,D).
I am glad it helped you. Consider also upvoting and accepting my answer if it helped you.
Your answer will be accepted after fixing the unbalanced { } issue. Thank you.
What do you mean { } issue?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.