2

I have the following structure in DynamoDB:

{
  "fruits": {
    "1": {
      "identifier": "orange",
      "colour": "orange"
    },
    "2": {
      "identifier": "strawberry",
      "colour": "red"
    }
  },
  "username": "my-username"
}

How do I add a '3rd fruit item' with its associated attributes? I am aiming to achieve the following:

{
  "fruits": {
    "1": {
      "identifier": "orange",
      "colour": "orange"
    },
    "2": {
      "identifier": "strawberry",
      "colour": "red"
    },
    "3": {
      "identifier": "pear",
      "colour": "green"
    }
  },
  "username": "my-username"
}

I have tried something similar to the following:

result = table.update_item(
    Key={
        'username': str('my-username')
    },
    UpdateExpression='set fruits.3.identifier = :i, fruits.3.colour = :c',
    ExpressionAttributeValues={
        ':i': 'pear',
        ':c': 'green'
    }
)

Thank you!

1 Answer 1

2

You cannot directly set attributes such as fruits.3.identifier because fruits.3 does not exist yet. Instead, you must set fruits.3 as a whole object.

Your update expression should be something like this:

result = table.update_item(
    Key={
        'username': str('my-username')
    },
    UpdateExpression='set fruits.3 = :newFruit',
    ExpressionAttributeValues={
        ':newFruit': {
            'colour': 'green',
            'identifier': 'pear'
        }
    }
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.