Remove documents from all collections in the db that have a specific Id

So in our app when a user deletes a project we go to each of the collections that have that specific project’s documents and delete them
Like deleting all their data from each collection

So I was wondering if its possible to delete all records from all collections based on a filter in one query

db.allCollections.deleteMany({id:123})

Some thing like this where all collections is gonna go to each collection and remove documents

Hi @AbdulRahman_Riyaz

So I was wondering if its possible to delete all records from all collections based on a filter in one query

No I don’t believe such a method exists today. You would have to go into each collection, and execute the delete command in each of them. Something like:

for x in [list of collection names]:
    db[x].deleteMany( <some condition> )

However note that you’ll also need to cover the case of interruptions with the command (replica set elections, network issues, etc.) where there’s a possibility that not all collections were processed. This would lead to some orphaned documents that may need extra cleanup steps.

I imagine if such a command exist, it will be a pretty dangerous command. Also depending on the number of collections you have, it could have a non-trivial running time that’s dfifficult to predict.

Hope this helps!

Best regards
Kevin

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.