0
0
DynamoDBquery~5 mins

Expressions with SDK helpers in DynamoDB

Choose your learning style9 modes available
Introduction

Expressions help you tell DynamoDB what data to work with in a clear and safe way.

When you want to update an item without replacing the whole thing.
When you want to filter items based on certain conditions.
When you want to add or remove attributes from an item.
When you want to avoid mistakes with reserved words in DynamoDB.
When you want to write cleaner and easier-to-read code for database actions.
Syntax
DynamoDB
import { UpdateCommand } from "@aws-sdk/lib-dynamodb";

const params = {
  TableName: "YourTable",
  Key: { id: "123" },
  UpdateExpression: "set #name = :nameValue",
  ExpressionAttributeNames: { "#name": "name" },
  ExpressionAttributeValues: { ":nameValue": "New Name" }
};

const command = new UpdateCommand(params);
await client.send(command);

Use ExpressionAttributeNames to avoid conflicts with reserved words.

Use ExpressionAttributeValues to safely pass values.

Examples
Update the age attribute to 30.
DynamoDB
UpdateExpression: "set age = :newAge",
ExpressionAttributeValues: { ":newAge": 30 }
Filter items where the tags list contains "urgent".
DynamoDB
FilterExpression: "contains(#tags, :tagValue)",
ExpressionAttributeNames: { "#tags": "tags" },
ExpressionAttributeValues: { ":tagValue": "urgent" }
Remove the attribute named oldAttribute from the item.
DynamoDB
UpdateExpression: "remove #oldAttr",
ExpressionAttributeNames: { "#oldAttr": "oldAttribute" }
Sample Program

This code updates the nickname attribute of the user with ID "user123" to "CoolUser". It uses expression helpers to safely name the attribute and value.

DynamoDB
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, UpdateCommand } from "@aws-sdk/lib-dynamodb";

const client = new DynamoDBClient({ region: "us-east-1" });
const ddbDocClient = DynamoDBDocumentClient.from(client);

async function updateItem() {
  const params = {
    TableName: "Users",
    Key: { userId: "user123" },
    UpdateExpression: "set #nickname = :nick",
    ExpressionAttributeNames: { "#nickname": "nickname" },
    ExpressionAttributeValues: { ":nick": "CoolUser" },
    ReturnValues: "UPDATED_NEW"
  };

  const command = new UpdateCommand(params);
  const result = await ddbDocClient.send(command);
  console.log(result.Attributes);
}

updateItem();
OutputSuccess
Important Notes

Always use expression attribute names and values to avoid errors with reserved words or special characters.

Expressions make your updates and queries safer and clearer.

Summary

Expressions tell DynamoDB exactly what to do with data.

Use SDK helpers to write expressions safely and clearly.

They help avoid mistakes and make your code easier to read.