Reputation: 5203
I have a reviews collection and a users collection. In the users collection I have docs that have an array called reviews
that contains the _ids of the review from the reviews collection. Sometimes I go to the mongo terminal and delete reviews from the reviews collection that I don't want from the reviews collection. for example I would delete all that don't have a specific field. the problem is I would also like to delete the review id in the reviews array. I do a simple db.collection.remove
on the reviews collection so that is easy.(that would delete like 50 reviews). I was wondering how to remove ids in the reviews array easily. Any ideas? I use mongoose but I was wondering if there was an easy way to do in the terminal. I think the only association is the ids.
I no how to use $pull but I want to make it pull the ids every time a specific review is removed.
Upvotes: 1
Views: 1407
Reputation: 103305
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 } }
);
Upvotes: 2