4

How can I update an array in a mongoDB document by index, which is stored in a variable?

{
    _id: 'IDString',
    field: [ bla, bla, old, bla ];
}

let i = 2;
Collection.update(
    { _id: 'IDString' },
    { $set: 
        { 'field.$.i': 'new' }
    }
);

So the result should be:

{
    _id: 'IDString',
    field: [ bla, bla, new, bla ];
}

My code wouldn't work, as I want to use the variable i.

1

2 Answers 2

2

Use the dot notation syntax to set up your update document since this will access an element of an array by the zero-based index position. You would have to concatenate the array name with the dot (.) and zero-based index position, and enclose in quotes.

So in your example, you would need to set up the update document dynamically to produce

var update = { "$set": { "field.2": "new" } }

The following code snippet shows this:

var i = 2,
    update = { "$set": {} };

update["$set"]["field."+i] = "new";
db.collection.update({ "_id": "IDString" }, update)
Sign up to request clarification or add additional context in comments.

1 Comment

Great solution! The same dictionary string approach helped me out in pymongo as well. Here it is formatted for readability. I dislike dealing with variables and functions with the same name. var i = 2; var arr_update_dict = { "$set": {} }; arr_update_dict["$set"]["field."+i] = "new"; db.collection.update({ "_id": "IDString" }, arr_update_dict)
0
Collection.update(
    { _id: 'IDString', field.2 : 1 },
    { $set: {
        "field.$" : "new" }
    }
)

This should work, if not - comment below

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.