Tndfr
Tndfr

Reputation: 23

inserting a nested attributes array element in dynamodb table without retrieving the entire item

looking for an answer to this question if possible, not looking for a refactoring advice or redesign, i just need to understand what else I am missing here :

I have an existing item in dynamodb:

{
"CartId": 321,
"UserId": usr555,
"CartItems": [
 {
    "ProductId":59999,
    "Quantity": 1
 },
 {
    "ProductId": 58888,
    "Quantity": 2
 }
 ]

}

in my code I want to insert another nested attribute into the array CartItems in the item above. i can't find a way of doing this without retrieving the entire item and then inserting, which could amount to KBs in size.

all I want to do is insert a single array element in an existing nested attribute without having to retrieve the item.

the language I am using is nodejs and the function is DynamoDB.put.

Upvotes: 2

Views: 1079

Answers (1)

omuthu
omuthu

Reputation: 6333

UpdateExpression attribute supports SET action and SET action supports list_append function. Since list_append function operands must be list, enclose the new value within a list as below.

response = dynamodb_client.update_item(TableName='your_table', 
Key={'CartId':'321'}, 
UpdateExpression='SET CartItems = list_append(CartItems, :val1)',
ExpressionAttributeValues = {':val1':[{'ProductId':12345, 'Quantity': 100}]})

Hope this helps

Upvotes: 2

Related Questions