As a rule of thumb, we should never run database queries inside a for-loop! For example, let’s say we designed an inventory software and it’s being used in production for a year, and reached 1,000,000 transactions.
If we had small number of transactions, we could do: However, running it in a loop of 1 million and making a “database transaction” in each iteration of the loop — not a good idea!
Chunk” your collection to separate your transaction to multiple database transactions.
Here, first we divide our $transactions collection into 5000 chunks and we do a “database transaction” per 5k records at once.