Selecting and deleteing collcection documents

I am trying to select every document in a list of collections in my database where it has a particular field value

What have you tried so far?

const itemId = “item_id”;

const collections = ["Collection1", "Collection2", "Collection3", "Collection4"];
for (const collectionName of collections) {
  const documents = await collectionName .deleteMany({itemId: itemId})

but i do not want to use a loop because of performance, 50 users could be requesting the same thing at the same time

I’m not sure that’s possible then, running a delete at a database level. How unique is itemID? I assume it’s indexed, have you done any testing to verify your scenario of if this will bottleneck if it’s called 50 times simultaniously?

I assume you’re running node, why not call deletes on all collections at the same time and then wait for them all to complete?

The time spent looping over the list of collections on your client code will be insignificant compared to the work that has to be done on the server during any major deleteMany.

It might even help distribute over time the work that has to be done by the server. The side effect being less CPU spike and better response time for other less intensive use-cases.

You are worrying too much. Early optimization is often a mistake. Implement the simplest algorithm first and optimize if is a frequent bottleneck.

The code you share looks like a cleanup code when an account is delete or something like that. That is probably not a frequent use-case. You probably would want to throttle that and use some king of notification rather than have a user waiting for the operation to complete.

1 Like