Modifying the last element of an array in MongoDB

arrays, mongodb

Solution

I don't know of a way to do this using a single-line query. But you could select the record, update and then save it.

var query = <insert query here>;
var mydocs = db.mycollection.find(query);
for (var i=0 ; i<mydocs.length ; i++) {
    mydocs[i].pockets[pockets.length-1].items.push('new item');
    db.mycollection.save(mydoc);
}

Problem

I have an object structure like this: ``` { name: "...", pockets: [ { cdate: "....", items: [...] } ... ] } ``` In an update operation, I want to add some records into the items field of the last pocket item. Using dot notation is the only way that I know to access a sub document, but I can't get what I want. So, I'm looking for something like these: - pockets.-1.items - pockets.$last.items Is it possible to modify the last element? If yes, how?

Original source