Thursday, February 6, 2014

MongoDB Updating Entry in Array Within Document

This is done via the "$pop" operation but most examples out there operate on simple objects. Here's how it's done for an array that's deeper within the document.

So e.g. if we have a document like this in the "workshop" collection:


{
"_id" : ObjectId("51e216e55cf2ff1231dee123"),
"info" : {
"name" : “Workshop X”,
"city" : “Sacramento”
}
"inventory" : {
"cars" : [
{
"licensePlate" : "XXXX01",
"make" : “Toyota”
},
{
"licensePlate" : "XXXX02",
"make" : “Kia”
},
{
"licensePlate" : "XXXX03",
"make" : “Hyundai”
},
{
"licensePlate" : "XXXX04",
"make" : “Nissan”
},
{
"licensePlate" : "XXXX05",
"make" : “Honda”
}
]
}
}



We could remove the entry at the bottom of the array with the command:

db.workshop.update({"info.name":"Workshop X"} ,{$pop:{"inventory.cars" : 1}});

Note that if you use the dot notation for accessing attributes deeper into the document, you'll need to surround the expression with quotes.

More documentation on $pop here: http://docs.mongodb.org/manual/reference/operator/update/pop/#up._S_pop

No comments:

Post a Comment