3

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

9 Comments

It always updates the first element with that, even though that isn't the correct element.
Even after adding the exact id match in find query "var1.var2.id": id?
prntscr.com/tkb05f as you can see there I even did it with string to make sure it was correct but still it always does the first element in the array.
yerp it finds it, it returns the whole object ofc
:clap: :clap: That did the trick! await db.collection("collectionName").findOneAndUpdate( {"var1.var2.id": id}, { $set: { "var1.var2.$": updatedObject } } );
|
0

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

1 Comment

I believe that's only on the document. The id in the query is on a child object within the document.

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.