How to Use REMOVE in Update Expression in DynamoDB
In DynamoDB, use the
REMOVE clause in an UpdateExpression to delete one or more attributes from an item. The syntax is REMOVE attributeName, and you can list multiple attributes separated by commas to remove them in a single update operation.Syntax
The REMOVE clause in a DynamoDB UpdateExpression specifies which attributes to delete from an item. You write it as REMOVE attribute1, attribute2, .... Each attribute listed will be removed from the item if it exists.
This clause is part of the UpdateExpression parameter in the UpdateItem API call.
sql
UpdateExpression = "REMOVE attributeName1, attributeName2"Example
This example shows how to remove the attributes PhoneNumber and Address from a DynamoDB item with a given UserId.
javascript
const AWS = require('aws-sdk'); const dynamodb = new AWS.DynamoDB.DocumentClient(); const params = { TableName: 'Users', Key: { UserId: '123' }, UpdateExpression: 'REMOVE PhoneNumber, Address' }; dynamodb.update(params, (err, data) => { if (err) { console.error('Error updating item:', err); } else { console.log('Attributes removed successfully:', data); } });
Output
Attributes removed successfully: { Attributes: undefined, ConsumedCapacity: undefined, ItemCollectionMetrics: undefined }
Common Pitfalls
- Trying to remove a non-existent attribute: This does not cause an error; DynamoDB simply ignores it.
- Using
REMOVEwith incorrect attribute names: Attribute names must be valid and, if reserved words, must be replaced with expression attribute names (e.g.,#attr). - Mixing
REMOVEwith other update actions incorrectly: SeparateSET,REMOVE,ADD, andDELETEclauses with spaces in the sameUpdateExpression.
sql
/* Wrong: Using reserved word without expression attribute name */ UpdateExpression = "REMOVE Size" /* Right: Using expression attribute name for reserved word */ UpdateExpression = "REMOVE #sz" ExpressionAttributeNames = { "#sz": "Size" }
Quick Reference
| Clause | Purpose | Example |
|---|---|---|
| REMOVE | Deletes attributes from an item | REMOVE PhoneNumber, Address |
| SET | Adds or updates attributes | SET Age = 30 |
| ADD | Adds numbers or elements to sets | ADD Score 5 |
| DELETE | Removes elements from sets | DELETE Tags :tagToRemove |
Key Takeaways
Use the REMOVE clause in UpdateExpression to delete attributes from a DynamoDB item.
List multiple attributes separated by commas to remove them in one update call.
If an attribute does not exist, REMOVE does not cause an error.
Use expression attribute names for reserved words in attribute names.
Combine REMOVE with other update actions by separating clauses with spaces.