DEV Community

Abhishek Gupta for AWS

Posted on • Originally published at

[20 Days of DynamoDB] Day 5 - Avoid overwrites when using DynamoDB UpdateItem API

Posted: 12/Jan/2024

The UpdateItem API creates a new item or modifies an existing item's attributes. If you want to avoid overwriting an existing attribute, make sure to use the SET operation with if_not_exists function.

Here is an example that sets the category of an item only if the item does not already have a category attribute:

    resp, err := client.UpdateItem(context.Background(), &dynamodb.UpdateItemInput{
        TableName: aws.String(tableName),
        Key: map[string]types.AttributeValue{
            "email": &types.AttributeValueMemberS{Value: email},
        UpdateExpression: aws.String("SET category = if_not_exists(category, :category)"),
        ExpressionAttributeValues: map[string]types.AttributeValue{
            ":category": &types.AttributeValueMemberS{
                Value: category,
Enter fullscreen mode Exit fullscreen mode

Note that if_not_exists function can only be used in the SET action of an update expression.

Recommended reading - DynamoDB documentation

Top comments (0)