To find data in a table, you use the operations .query() and .scan(). Sometimes, you may only want to write the data if certain conditions are met. To do this, use the .where() modifier. Under the hood, .where() is setting the Condition Expression Param.
Example
Say you are representing a movie in DynamoDB like this...
{
id: '12345',
title: 'Fantastic Beast and Where to Find Them',
info: {
rating: 5,
should: 'climb'
},
shouldRecommend: false,
stars: ['Red headed dude', 'Johnny Depp']
}
and you only want to update the shouldRecommend
attribute if the rating = 5
d.table('Movies')
.update({id: '12345'})
.set({
shouldRecommend: true
})
.where({
info: {rating: 5}
})
.run();
For more complicated conditions, you can use condition statements
const positiveRating = attr({info:{rating:true}}).gt(5);
const harryOrFanMovie = attr('title').startsWith('Harry').or(
attr('title').startsWith('Fan');
);
d.table('Movies')
.update({id: '12345'})
.set({
shouldRecommend: true
})
.where(positiveRating.and(harryOrFanMovie))
.run();
This sets the shouldRecommend attribute if the rating is greater than 5 and the title starts with either 'Fan' or 'Harry'
See the Comparators section for a complete list
This gets translated into the following params that are passed to the AWS DocumentClient.
AWS DocumentClient
const params = {
ConditionExpression: '#r = :rating',
ExpressionAttributeNames: {
'#r': 'info.rating',
},
ExpressionAttributeValues: {
':rating': 5
}
}
AWS Documentation Links
Condition Expression Operators and Functions
Condition Expression
Expression Attribute Names