DEV Community

Abhishek Gupta for AWS

Posted on • Originally published at community.aws

6 1 1 1

[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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay