Deleting resources in cursor loop

Given a query result cursor, is it safe to delete/modify each item while iterating over the cursor?

I run a query and get a cursor, for each of the result, I want to modify (“replace”) the found resource, or delete it.

Is this a safe operation? Or am I required to finish iterating over ALL the results and only then make the changes?

I’m using the Node SDK, if it matters.

Hi @Nathan_Hazout!

Good news: It’s a safe operation. Running a find query against a collection doesn’t imply a lock on the data in the database, so you can execute updates or deletes at any time.

Thanks so it doesn’t affect the cursor?
Deleting an item doesn’t make the cursor jump back or forth, somehow modifying the underlying data that backs the cursor ?

When you read a cursor it actually calls getmore behind the scenes to get a batch of results. Each batch of results is copied from the database. Once they are in memory writes or deletes may affect the contents of the database independent of your query. So you might be reading a result which in reality has been deleted. If you want to guarantee that results are not being modified while they are being read you should enclose the query in an transaction.

1 Like