In my recent project, I needed to update a single value in a nested object for a document on DynamoDB. In other projects, I would update the nested object property and then Save the whole document using SaveAsync from IDynamoDBContext. However, in this project, it needs to update the document from another microservice and I didn’t want to copy the model from that other microservice. This is because I only need to update one property and I don’t want this to have the knowledge of the whole model.
In this short post, I will show how I achieved this. Let’s say the model of our document looks like this.
[DynamoDBTable("books")]
public class Book
{
[DynamoDBHashKey]
public Guid Id { get; set; }
public string Name { get; set; }
public Publisher Publisher { get; set; }
}
public class Publisher
{
public Guid Id { get; set; }
public string Name { get; set; }
}
Let’s say we need to update the name of the publisher for a given Document ID. I have a method to update it like this.
private readonly IAmazonDynamoDB _ddbClient; // This will be injected via DI
public async Task UpdatePublisherName(Guid bookId, string publisherName)
{
await _ddbClient.UpdateItemAsync(new UpdateItemRequest
{
TableName = "books",
UpdateExpression = "SET #ps.#n = :name",
Key = new Dictionary<string, AttributeValue>
{
{ "Id", new AttributeValue(bookId.ToString()) },
},
ExpressionAttributeNames = new Dictionary<string, string>
{
{ "#ps", "Publisher" },
{ "#n", "Name" }
},
ExpressionAttributeValues = new Dictionary<string, AttributeValue>
{
{ ":name", new AttributeValue(publisherName) }
}
});
}
The method does not need to reference the Book model. It only needs to know about the part it needs to update.