Home > Net >  Update a value in array of objects MongoDb
Update a value in array of objects MongoDb

Time:06-02

    {
      "name": "user2",
      "avatar": 1,
      "email": "[email protected]",
      "categories": [
        {
          "cname": "Category 1",
          "list": [
            {
              "status": "pending",
              "name": "List Item 1"
            },
            {
              "status": "pending",
              "name": "List Item 2"
            }
          ]
        }
      ]
    }

I want to update "categories.list.status" = "pending" to "completed". How can I do it? I tried using positional operator($) but it is giving error too many positional operator.

CodePudding user response:

If you are using Mongoose (as your tags suggest), you can just update the value in the document object and then save it

document.list[0].status = "completed";
document.save();

CodePudding user response:

I tried this. It worked.

    document.updateOne({_id: id}, {
    {
        $set: {
              "categories.$[].list.$[ele].status" : status
             }
    },
    {
        arrayFilters: [{"ele.name" : name}]
    }
    }
  • Related