Delete documents from collection and remove Ids from an array in another collection Delete documents from collection and remove Ids from an array in another collection mongoose mongoose

Delete documents from collection and remove Ids from an array in another collection


You certainly can't do this with a single atomic update as you have two collections to update. What you can do is carry out two operations in series i.e. the removal of the specific reviews from the reviews collection and then use the $pullAll operator to delete the values from reviews array in the users collection.

The following mongo shell example shows this:

var reviewIds = [    ObjectId("582ebf010936ac3ba5cd00e2"),    ObjectId("582ebf010936ac3ba5cd00e3"),    ...];db.reviews.remove({ "_id": { "$in": reviewIds } });db.users.updateMany(    { "reviews": { "$in": reviewIds } },    { "$pullAll": { "reviews": reviewIds } });

For a single review id, you can just use the $pull operator as

db.reviews.remove({ "_id": reviewId });db.users.updateMany(    { "reviews": reviewIds },    { "$pull": { "reviews": reviewId } });