0
0
DynamoDBquery~5 mins

SET expression for adding/changing in DynamoDB

Choose your learning style9 modes available
Introduction

The SET expression lets you add new attributes or change existing ones in a DynamoDB item.

You want to update a user's email address in a user profile.
You need to add a new field like 'lastLogin' to an existing record.
You want to increase a numeric counter stored in an item.
You want to change the status of an order from 'pending' to 'shipped'.
Syntax
DynamoDB
UpdateExpression: "SET attributeName = :value, anotherAttribute = :anotherValue"
Use 'SET' to add or change attributes in an item.
Use placeholders like ':value' for the new values to keep the query safe.
Examples
Change the 'age' attribute to a new value.
DynamoDB
UpdateExpression: "SET age = :newAge"
Add or update 'lastLogin' and 'status' attributes at the same time.
DynamoDB
UpdateExpression: "SET lastLogin = :time, status = :newStatus"
Increase the 'score' attribute by a number.
DynamoDB
UpdateExpression: "SET score = score + :increment"
Sample Program

This updates the user's email and increases their login count by 1. If 'loginCount' does not exist, it starts at 0.

DynamoDB
const params = {
  TableName: "Users",
  Key: { userId: "123" },
  UpdateExpression: "SET email = :newEmail, loginCount = if_not_exists(loginCount, :start) + :inc",
  ExpressionAttributeValues: {
    ":newEmail": "new.email@example.com",
    ":start": 0,
    ":inc": 1
  },
  ReturnValues: "UPDATED_NEW"
};

// Assume docClient is an instance of AWS.DynamoDB.DocumentClient

const result = await docClient.update(params).promise();
console.log(result.Attributes);
OutputSuccess
Important Notes

Use if_not_exists to safely add numbers when the attribute might not exist yet.

Always use placeholders (like :newEmail) to avoid injection and errors.

Summary

SET expression updates or adds attributes in DynamoDB items.

Use placeholders for values to keep queries safe and clear.

You can update multiple attributes in one SET expression.