Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: Replace object in array

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.

like image 253
Bas950 Avatar asked Jul 27 '26 12:07

Bas950


1 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.

like image 164
Prathap Reddy Avatar answered Jul 30 '26 04:07

Prathap Reddy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!