Delete embedded document from array

Hello,

I’m trying to delete a single entry in my array of “unions”, it’s marked orange in the screenshot:

I have tried to delete it with a delete query by using the the embedded documents “_id”. But then the whole toplevel document is beeing deleted aswell. After some searching i know this is just the way MongoDB works.

Is there a way i can accomplish this?

Hi @SaltyPigeon,

You can use an update / updateOne Query in combination with the $pull operator:
Something like that:

db.“your_collection”.updateOne( { _id: “your_root_id” }, { $pull: { “unions”: { “_id”: “array_id” } }} )

For more: https://www.mongodb.com/docs/manual/reference/operator/update/pull/

Hope this helps!

Greetings,
Niklas

2 Likes

Thanks for the fast reply.

This solution seemes to make a lot of sense, i will try this first thing tomorrow!

I will let you know if it worked :smile:

@NiklasB works like a charm!!

Adding the “root_id” of the document did the trick, as i reviewed my old code i actually worked with the $pull operator but the missing root id was the faulty chain here!

Thanks for the great help :partying_face: :partying_face:

SaltyPigeon :salt::bird:

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.