findAndModify multiple documents

Hi! I would like to lock a batch of documents for processing in an application consisting of multiple instances. While one instance has selected a batch of documents for further processing, other instances should not be able to select it.

findAndModify appears to be a perfect solution, but it only chooses a single document from the query, then updates it and returns the original version.

What I need, is a similar method for a batch of documents. It should in particular:

  1. Update or lock a batch of documents in a single operation,
  2. Allow to set a limit to the batch size,
  3. Return the batch for further processing.

Is there any way to accomplish this challenge?

Hello @Piotr_Kwiatkowski,

Welcome to MongoDB community! :wave:

I notice you haven’t had a response to this topic yet - were you able to find a solution?
If not, could you please help me understand below things from your use-case?

What is select in this context?
is this a read operation (other transactions should not be able to read)?
or are you referring to a write operation here?

Can you elaborate on this?

I think what you are describing so far can be solved using Transactions, where a series of operations are executed in its entirety, or none of them, and they are treated as a singular operation. Note that multiple operations (including findAndModify) can be executed within a transaction. For more information, please see:

This is correct but you can get the updated version instead of origina, by setting new: <boolean> to true, the default is false.

If you need further information, could you please provide:

  • MongoDB version and driver version (if any)
  • Deployment type (e.g. standalone, replica set, sharded cluster)
  • Example process of your use-case

Regards,
Tarun

1 Like