What you'll learn
- UpdateItem changes only the attributes you name, and it creates the item if the key doesn't exist yet (add a condition like
attribute_exists(#name)to prevent that). - Use UpdateExpression to define what changes to make (SET, REMOVE, ADD).
- ExpressionAttributeValues act as variables to keep your expressions clean and secure.
Section 01
The Power of UpdateItem
Unlike PutItem, which replaces the entire item, UpdateItem allows you to modify specific attributes. This is efficient because you don't need to send the whole item payload back to DynamoDB.
You use an UpdateExpression to tell DynamoDB exactly what to do. The most common action is SET.
- SET: Overwrites an attribute or creates it if it doesn't exist.
- REMOVE: Deletes an attribute from the item.
- ADD: Adds to a number (atomic counter; a missing attribute starts at 0) or adds elements to a set.
- DELETE: Removes elements from a set.
Ready · 5 steps · Orbi
This animation plays when you scroll to it. Press Play to start it now.
All steps as text
- Your app sends PutItem to the Pokemon table with Name = "Mew". Using PutItem with just Name and Level instead of UpdateItem.
- DynamoDB hashes "Mew" to 416a585c, which routes the request to partition P0.
- Your app's write to Mew lands on P0 and silently replaces the other change.
- This call consumed 1 WCU.
- DynamoDB responds with success: PutItem replaced the whole item, so Mew lost its Type and Status.
Section 02
Using Expression Attributes
To prevent injection attacks and handle reserved words safely, DynamoDB uses placeholders in expressions. You define the placeholder in the expression and bind the actual value in ExpressionAttributeValues.
Here, :newLevel is a placeholder. DynamoDB swaps it with the value 6 safely at runtime.
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, UpdateCommand } from "@aws-sdk/lib-dynamodb";
const client = new DynamoDBClient({ region: "ap-south-1" });
const docClient = DynamoDBDocumentClient.from(client);
await docClient.send(new UpdateCommand({
TableName: "Pokemon",
Key: { Name: "Mew" },
ExpressionAttributeNames: { "#level": "Level" },
UpdateExpression: "SET #level = :newLevel",
ExpressionAttributeValues: {
":newLevel": 6
}
}));Practice
Your turn
UpdateCommand to change its Level without rewriting the rest of the item: fill in UpdateExpression and ExpressionAttributeValues, and add ExpressionAttributeNames: { "#level": "Level" } because Level is a reserved word.UpdateExpression to set Mew's Level to 6.Check
Check your understanding
Quick Quiz · one question, as many tries as you need.
Choose one answer.