insert to specific index for mongo array

Viewed 10142

Mongo supports arrays of documents inside documents. For example, something like

{_id: 10, "coll": [1, 2, 3] }

Now, imagine I wanted to insert an arbitrary value at an arbitrary index

{_id: 10, "coll": [1, {name: 'new val'}, 2, 3] }

I know you can update values in place with $ and $set, but nothing for insertion. it kind of sucks to have to replace the entire array just for inserting at a specific index.

5 Answers

The following will do the trick:

var insertPosition = 1;
var newItem = {name: 'new val'};

db.myCollection.find({_id: 10}).forEach(function(item)
{
    item.coll = item.coll.slice(0, insertPosition).concat(newItem, item.coll.slice(insertPosition));
    db.myCollection.save(item);
});

If the insertPosition is variable (i.e., you don't know exactly where you want to insert it, but you know you want to insert it after the item with name = "foo", just add a for() loop before the item.coll = assignment to find the insertPosition (and add 1 to it, since you want to insert it AFTER name = "foo".

Related