Locking Documents In Mongo

Hi @Jason_Widener,

In MongoDB we recommend using the findAndModify command for this scenario.

This command is atomic and thus lock the document for a status change.

Each service instance should do:

db.coll.findAndModify({id : "doc1", status : "pending"},{$set : { status : "processing"}});

This way only one service only will see the pending document.

If the processing fails you can change the status back to pending and sort by creation datefor another service to pick it up.

If there is a more complex logic consider using transactions.

Please let me know if you have any questions.

Best regards
Pavel

2 Likes