Removing an element from an array in a MongoDB document with Spring Boot
Problem
How can I update a MongoDB document removing an element from a field array ?
Solution
The MongoDB document to update.
{
"_id" : ObjectId("66e00a4fe1f9692e80132fcf"),
"name" : "Gandalf",
"type" : "Wizard",
"inventory" : [
{
"id" : 1,
"name" : "Red Spell",
"counter" : 3
},
{
"id" : 2,
"name" : "Blue Spell",
"counter" : 0
},
{
"id" : 3,
"name" : "Green Spell",
"counter" : 1
}
]
}
The MongoDB query to remove an element from the inventory
field is the following:
db.getCollection('players')
.update({_id:ObjectId("66e00a4fe1f9692e80132fcf")}, { $pull: { 'inventory': { "id": 2 } } } )
and this is the related Spring Boot Data code.
Criteria crit = Criteria.where("id").is("66e00a4fe1f9692e80132fcf");
Update update = new Update();
update.pull("inventory", new BasicBSONObject("id", 2));
mongo.updateFirst(new Query(crit), update, PlayerDocument.class);```