0

I have a collection of documents similar to the following:

{
    _id: ObjectId("..."),
    title: "...",
    body: "...",
    comments: [
        {
            name: "...",
            email: "...",
            comment: "..."
        },
        {
            name: "...",
            email: "...",
            comment: "..."
        },
        {
            name: "...",
            email: "...",
            comment: "..."
        }
    ]
}

Let's say that I want to update the name field for the second comment. So, I would have a query as follows:

db.posts.update({_id: ""}, {$set: {"comments.2.name": "new name"}});

Now, I'm wondering how could I pass the index of array element (2) as a parameter/variable in node.js?

1 Answer 1

2

The answer to this is to simply construct the object in code. Object keys stringify in JavaScript and most other languages supporting the notation, so simply build the string externally and use the Object notaion methods:

var index = 1,  // n-1 for array index notation of the second element
    name = "new name";


var update = { "$set": { } },
    query = {};

update["$set"]["comments." + index + ".name"] = name;

// Then update as normal
db.posts.udate(query,update);

That builds an object using the correct "dot notation" format

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

2 Comments

@moorara Of course it works, it's standard JavaScript notation. You are probably doing something like this: { "$set": { "comments." + index + ".name": name } }, and that is incorrect and does not work. The MongoDB shell is a REPL. Just type it in any you will clearly see the object is formed correctly.
how can you do this inside an update hook when you have the $set modifier: modifier.$set.myArray.index.value where index is the position of the element to update and value is what i want to set?

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.