phadaphunk
phadaphunk

Reputation: 13283

Remove only the sub element from a find

Is there a way to delete only the subdocument found at the bottom of my search parameters?

Let's say I have this query :

const diagnostics = await Diagnostic.find({
      'stepListings.steps.apps': { "$elemMatch": { '_id': "5ed1439ffc2b530012deafd3" } } 
});
  

It will give me all Diagnostic items that fit the following requirements (one of it's steplistings, has at least one of the steps that has an app with and _id of "5ed1439ffc2b530012deafd3") so I can get multiple Diagnostics here. If I remove with this query filter, it will delete from the root document (the whole Diagnostic in this case) Is there a way to remove only the very bottom of the search (the app within the steps in this case) so that I keep the Diagnostic, it's steplistings and it's steps but loose the app with the desired _id.

I can do the thing in the long way by looping through diagnostics, then steplistings...steps..apps and splice the app from there but it is a lot of looping for something that can probably be done in a one liner.

Upvotes: 0

Views: 56

Answers (1)

Cuong Le Ngoc
Cuong Le Ngoc

Reputation: 11975

In case your stepListings, steps and apps are all arrays, you can use $pull with The all positional operator $[] to solve the problem. Something like:

Diagnostic.updateMany(
  {'stepListings.steps.apps._id': "5ed1439ffc2b530012deafd3" },
  {
    $pull: {
      'stepListings.$[].steps.$[].apps': {_id: "5ed1439ffc2b530012deafd3"}
    }
  }
);

Upvotes: 1

Related Questions