MikeyB
MikeyB

Reputation: 490

Update 1 or more array items in Mongodb document by Index

I am pretty new to mongodb and am trying to figure out some slightly more precise queries. This is on a node.js server.

I want to update an array within an existing document by 1 or more indexes. The mongodb docs really don't help a beginner with their syntax, hoping you can help.

    let updateArray = [
        {index:2,text:'boo',insert:false},
        {index:4,text:'bar',insert:true},
        {index:7,text:'bop',insert:false}
    ]
    db.collection(user).findAndModify(
        {_id:ObjectId(_id)},
        { $set: { "array.$[index].text": updateArray[index] } },
        { arrayFilters: updateArray, new: true }
    ) 

Obviously this hasn't worked. Was shooting for the moon with it but it's an example of the kind of thing I'd like to achieve with one query. Hope it's clear enough for someone more experienced than me to at least point me in the right direction. Thanks!

EDIT: After comment below, this is what I have before:

{
    array : [
        "boo boo",
        "boppidy"
    ]
}

and after:

{
    array : [
        "boo boo",
        "bar bar"
        "boppidy bop"
    ]
}

Notice I want to push to an index as well as set a new value for another. Current code after finding useful hints gives this but I am getting an Updating the path 'array' would create a conflict at 'array', which kind of makes sense but don't know what the way around would be.

db.collection(user).update(
        {_id:ObjectId(_id)}, {   
            $set :  {
                "array.2" : "boppidy bop"
            },
            $push:{
                "array":{
                    $each: ["bar bar"],
                    $position:1 
                    }
                }
        }
)

Upvotes: 0

Views: 66

Answers (0)

Related Questions