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

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

Top comments (0)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay