Search code examples
node.jsamazon-web-servicesamazon-dynamodbaws-sdkdynamodb-queries

DynamoDB Table Count using Nodejs


I need to get count of records in my DynamoDB table using Node.js?

Simply, How to write Node.js snippet for same?

aws dynamodb scan --table-name dev-xxx-table --select "COUNT"

Tried https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#query-property

const params = {
    TableName: Table(),
    Select: COUNT
  }

  try {
    const count = await dynamoDb.query(params).promise()

but got

"ReferenceError: COUNT is not defined",

I couldn't find anything in the documentation for the same(or finding aggregation for DynamoDB table). Any lead will be appreciated.


Solution

  • Seems to me like there's two errors in the code, first you're using the wrong function (query instead of scan) and second, you're not passing COUNT as a String, but as a variable, which is why you're getting the error. Try the following code (untested):

    const params = {
      TableName: Table(),
      Select: "COUNT",
    };
    const count = await dynamoDb.scan(params).promise();
    

    That being said, be aware that this is a very expensive and probably slow operation that you do not want to be doing on a very large dataset.