简体   繁体   中英

update array in mongoDB document by variable index

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 .

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)
Collection.update(
    { _id: 'IDString', field.2 : 1 },
    { $set: {
        "field.$" : "new" }
    }
)

This should work, if not - comment below

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM