user2444499
user2444499

Reputation: 767

mongodb: how to update multiple fields in a nested array item of a single document

[
  {
    _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 }
        );

Upvotes: 2

Views: 3241

Answers (1)

Shubham Dixit
Shubham Dixit

Reputation: 1

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" } } )

Upvotes: 3

Related Questions