0

I want to update nested array in Mongo DB (using Node.js). I am able to get the array index location.

How can I update same ? I am facing some problem while using escape character in $set

Here is what I am doing :

testCollection.update({
        "uniqueID": someID,
        "topLevelObject.innerObjectValue": innerObjectVal
    }, {
        $set: {

            'array.' + outerArrayIndex + '.value': updatedValue,

        }

    }, function(err, result) {

        if (err) {
            console.log("Error occurred while updating db info");
        }

    }
);

1 Answer 1

2

It's hard to tell what the problem is because you have not included an example document or shown an error message or what goes wrong. Assuming your document looks like

{
    "_id" : 0,
    "array" : [{ "value" : 2 }, { "value" : 6 }]
}

then your above query should work, e.g.

db.test.update({ "_id" : 0 }, { "$set" : { "array.1.value" : 906 } })

will modify the document to

{
    "_id" : 0,
    "array" : [{ "value" : 2 }, { "value" : 906 }]
}

I omitted the other query condition because it isn't necessary with a unique id specified - perhaps the condition isn't matching any documents?

If you document looks like

{
    "_id" : 0,
    "array" : [2, 6]
}

then you don't need the .value in the update query:

db.test.update({ "_id" : 0 }, { "$set" : { "array.1" : 906 } })

I'd also check that the string concatenation with the variable outerArrayIndex is producing the correct field path.

Sign up to request clarification or add additional context in comments.

2 Comments

yeah , you are right . I forgot to mention the document structure , but it is exactly same . Never mind , I retrieved the index after doing a find operation , then converting the result to an array and then iterating through it. I am really new to NoSQL db , pardon my ignorance. Is there any better way to design the structure ? so that I do not need to iterate
I have the same problem, but mine is maybe worse. Because my data has a very deep nested structure, which makes update really hard

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.