Search code examples
javascriptmongodbnested

I am trying to perform a pull on a nested document, for all users in the collection, in which that nested document has a matching eventId field


I want to pull a nested document in the userSignedUpEvent field that matches the given eventId. The part that is giving me a hard time is that I want to run this for all users in the users collection. Because many users will have signed up for this event and if it gets removed I need to remove it from every user's userSignedUpEvents field.

Example User Doc:

{
  "_id": {
    "$oid": "636c1778f1d09191074f9690"
  },
  "name": "Wayne Wrestler",
  "email": "wakywayne80@gmail.com",
  "image": "https://lh3.googleusercontent.com/a/ALm5wu32gXjDIRxncjjQA9I4Yl-
  "userSignedUpEvents":[
        0:{
              eventId: 636c1778f1d09191074f9690
              eventName: "onmygod"
}
]
}

Attempts:

db.users.updateMany({"userSignedUpEvents.eventId": ObjectId('636c2c6dcb82e7ae6aac0960')}, 

{$pull: {"userSignedUpEvents.$[el]": true}}, {arrayFilters:[{"el.eventId":ObjectId('636c2c6dcb82e7ae6aac0960')}]})
db.users.updateMany({"userSignedUpEvents": {$elemMatch: {eventId: ObjectId('636c2c6dcb82e7ae6aac0960')}}}, 

{$pull: {"userSignedUpEvents.$.eventId": ObjectId('636c2c6dcb82e7ae6aac0960')}})

Solution

  • One option is:

    db.users.updateMany(
      {userSignedUpEvents: {$elemMatch: {eventId: eventId}}},
      {$pull: {userSignedUpEvents: {eventId: eventId}}},
    )
    

    See how it works on the playground example

    EDIT: Another option is:

    db.collection.update(
      {userSignedUpEvents: {$elemMatch: {eventId: eventId}}},
      [
        {$set: {
          userSignedUpEvents: {
            $filter: {
              input: "$userSignedUpEvents",
              cond: {$ne: ["$$this.eventId", eventId]}
            }
          }
        }}
      ],
      {multi: true}
    )
    

    See how it works on the playground example