DEV Community

Abhishek Gupta for AWS

Posted on • Originally published at community.aws

3 1 1 1

[20 Days of DynamoDB] Day 4 - Conditional UpdateItem

Posted: 11/Jan/2024

Conditional operations are helpful in cases when you want a DynamoDB write operation (PutItem, UpdateItem or DeleteItem) to be executed based on a certain criteria. To do so, use a condition expression - it must evaluate to true in order for the operation to succeed.

Here is an example that demonstrates a conditional UpdateItem operation. It uses the attribute_not_exists function:

    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 first_name = :fn"),
        ExpressionAttributeValues: map[string]types.AttributeValue{
            ":fn": &types.AttributeValueMemberS{
                Value: firstName,
            },
        },

        ConditionExpression:    aws.String("attribute_not_exists(account_locked)"),
        ReturnConsumedCapacity: types.ReturnConsumedCapacityTotal,
    })
Enter fullscreen mode Exit fullscreen mode

Recommended reading - ConditionExpressions

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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

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

Okay