Add or remove an entry from a List type attribute in a DynamoDB table item
The accepted answer is incorrect, the correct way of doing this is listed in the DynamoDB UpdateExpression documentation
You need to read the list then get the index of the item you're looking to remove then run REMOVE list[index]
as an UpdateExpression
You can use SET
operator to add element in the attribute list. But for that you have to retrieve the existing list first then append new element in the list. Suppose you have a attribute named active_user
which contain the list of active users.
previous_list = "#a"
query = "SET %s = list_append(%s, :new_user)" % (previous_list, previous_list)
user_table.update_item(
Key={
# primary key
},
UpdateExpression=query,
ExpressionAttributeNames={
'#a': 'active_user',
},
ExpressionAttributeValues={
':new_user': new_user_model
}
)
You can use REMOVE
operator to remove or delete an element of the list. But you have to find the index of the element because REMOVE
operator removes the given index of the list.
#user_index is the position of the target user in the list
query = "REMOVE active_user[%d]" % (user_index)
user_table.update_item(
Key={
# primary key
},
UpdateExpression=query
)
Here is REMOVE
operator doc and SET
operator doc.