You can find a document, update and return it using a single method: findAndModify. This is useful to deal with concurrency issues when multiple clients are trying to process documents from a collection and you don't want two of them processing the same one.

For example:

    query: { taken: { "$exists": false } },
    update: { taken: true }

This will safely return a single document that hasn't been taken by another process while marking it as taken.

By default, this method returns the document before the update, but you can add new: true to get the new one.

Previous on MongoDB
Mastodon Mastodon