Search code examples
amazon-web-servicesamazon-dynamodbaws-sdkdynamodb-queries

Update DynamoDB item only if the list doesn't contain the value


I’m using AWS SDK to query my DynamoDB table. I would like to update an item based on a conditional expression. If the value is not already existing in a list, I want to add it. 

Here are the params I’ve wrote:

var params = {
  TableName: "table_name",
  Key: {
    PartKey: "part_key",
    SortKey: "sort_key"
  },
  UpdateExpression: "SET MyList = list_append(MyList, :i)",
  ConditionExpression: "NOT contains(MyList, :i)",  
  ExpressionAttributeValues: {
    ":i": [new_value]
  } 
}

Unfortunately, it seems that my conditional expression is always satisfied (true) as even if the value I try to add to my list already exist, the update proceed and I get duplicate...


Solution

  • Your params should look like this:

    var params = {
        TableName: "table_name",
        Key: {
          PartKey: "part_key",
          SortKey: "sort_key"
        },
        UpdateExpression: "SET MyList = list_append(MyList, :i)",
        ConditionExpression: "NOT contains(MyList, :b)",  
        ExpressionAttributeValues: {
          ":i": [new_value], 
          ":b": new_value
        } 
    }