2
[
  {
    _id: "...",
    title: "some title",
    tasks: [
      { 
        id: "...",
        field1: "abc",
        field2: "def"
      },
      ...
    ]
  },
  ...
]

I would like to modify both field1 and field2 for a given task. I see lots of examples of how to update a single field, but not multiple fields.

I've tried the following, but it's simply replacing the whole task object with only the fields I'm setting.

    let changes = { field1: "123", field2: "456" };

    db.collection("lists")
        .updateOne(
            {   
                "_id": new ObjectId(req.params.listId), 
                "tasks.id": req.params.id 
            },
            { $set: { "tasks.$": changes } }
        );

Appreciate any help. Thanks.

WORKING SOLUTION

    let changes = { field1: "123", field2: "456" };
    Object.keys(changes).forEach(key => {
        changes[`tasks.$.${key}`] = changes[key];
        delete changes[key];
    });
    db.collection("lists")
        .updateOne(
            {   
                "_id": new ObjectId(req.params.listId), 
                "tasks.id": req.params.id 
            },
            { $set: changes }
        );

1 Answer 1

3

You have to follow query something similar like below to update the nested document inside an array. You have to give separate names for field1 and field2.Here is the document link

 db.collection.updateOne(
               {"_id": new ObjectId(req.params.listId),"tasks.id": req.params.id },
               { $set: { "tasks.$.field1":"xyz","tasks.$.field2":"mno" } } )
Sign up to request clarification or add additional context in comments.

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.