xxx_coder_noscope
xxx_coder_noscope

Reputation: 85

Mongodb lock collection until flag is set?

I have a simple collection with pre populated generated ids.

|task_id| used|
|      1| true|
|      2|false|
|      3|false|  

The idea is that i have a simple method that returns next task_id. getNextTaskId(), that sets used to true and returns task_id. But there might be concurrent calls for this method. How can i lock collection to prevent method from returning same task_id twice and prevent updating used to true twice, or more (for the same task_id)?

Upvotes: 1

Views: 1880

Answers (2)

Volodya Lombrozo
Volodya Lombrozo

Reputation: 3476

I think, the most appropriate approach for that case is using of Compound Operations.

For example, you can use something like this:

db.tasks.findOneAndUpdate({"used": {$ne: true}}, {$set: {"used": true}})

Implementations:

Upvotes: 2

D. SM
D. SM

Reputation: 14530

MongoDB does not provide a "lock collection" operation, because the database is designed for concurrency (and scale) and locking prevents both. There are various other strategies provided to satisfy various use cases.

See:

etc.

If you want a queue, use a queueing library in your language.

Upvotes: 2

Related Questions