MongoDB: Replace object in array

Viewed 1231

I am trying to replace/update a whole object in an array to it's latest values, but I cannot get it to work.

Db looks like this: (Note: there is only 1 main object in this collection)

    {
        "_id": {...},
        "something that doesnt matter": {...},
        "var1": {
            "var2": [{...}, {...}, {...}, {...}, {...}],
            "var3": [{...}, {...}, {...}, {...}, {...}]
        },
        "something that doesnt matter": {...}
    }

I need to update a certain object from array var2, I have the object ID or there is a custom ID in the object that I can also get it with (id == updatedObject.id)

This worked but I cannot get it to work with a custom array id

await db.collection("collectionName").findOneAndUpdate(
    {"var1.var2": { $exists: true }},
    { $set: { "var1.var2.1": updatedObject } }
);

I have the ID of the object already in the array on the db, but idk how to update it from var1.var2.ID,

so basically what I need is { $set: { "var1.var2.**ID**": updatedObject } } but I cant seem to find out how to get it to work.

Cause I dont want to update the whole array, and I also dont want to update a single variable in the object. I need to update the whole object.

Thank you in advance for your replies.

2 Answers

Have you tried as below

await db.collection("collectionName").findOneAndUpdate(
  {
    "var1.var2.id": id // id value (or any matching field) of object inside array you want to update
  },
  {
    $set: {
      "var1.var2.$": updatedObject // Update with new object
    }
  }
);

Hope this official mongodb documentation helps better for your requirement.

Sorry, I'm not able to comment but the above answer is almost correct except that you have to filter by var1.var2._id instead of var1.var2.id because mongodb default ID field is _id

Related