Delete object from multiple arrays during aggregation

Hi,

I have a collection with users. The “events” array is embedded in each user document. If an event is deleted globally, i want to run an aggregation that find all the docs with the event _id in them and then delete the event from each remaining document “events” array.

Something like this:

// users collection
[
    {
        name: "M",
        email: "",
        phone: "",
        events: [
            {
                  _id: "1234567"
            }
        ]
   },
   {
        name: "N",
        email: "",
        phone: "",
        events: [
            {
                  _id: "1234567"
            }
        ]
   },
   {
        name: "0",
        email: "",
        phone: "",
        events: [
            {
                  _id: "8907867"
            }
        ]
   }
]

say i want to delete event _id: 1234567 from the users who have that event in their embedded events array. How can i go about doing that with an aggregation pipeline? Or, is there a simpler way to achieve this?

You could probably use the $pull operator:

See examples in that page for something similar to your scenario.

This is to actually update the document, I assume you don’t just want to use aggregation queries to present data with explicit events removed each time?

1 Like

Hi John,

You are correct l, thank you!!