1

In node.js, suppose you have a sequence of asynchronous calls to MongoDB such as:

collection.find(query, projection).toArray(function(err, result) {

    var document = result[0];

    // Do something based off of fields in document...

    collection.update(...)(function(err, result) {

        // Do something...

    }); 
});

Will this entire block occur atomically? Or is interleaving possible when multiple calls are made to this method in quick succession?

My thoughts are: Since find is an asynchronous operation, it happens on some background thread. Therefore, a second call to this method may run the same find command and get the exact same result before the first call has a chance to update the document. The second call then has a stale reference to the document.

Is this correct or am I thinking about this all wrong?

1 Answer 1

3

No, this is not an atomic block of code. Calling into the code multiple times quickly can call find multiple times before updating and therefore not run the update you intend. MongoDB has atomic updates if you use the various update operators instead of reading values, updating them in code then writing the values back.

inc is the easiest one to use as an example. You could write code to read a number, increment it, then write the updated value back. However if that code was called concurrently, it could read the value twice, both calls increment the number to the same value, and one of those writes 'wins' - incrementing the value once instead of twice. Using inc however handles this case atomically (consider your write concern carefully).

To answer your question more specifically, the "Do something based off of fields in document..." needs to be something achievable using MongoDB update operators.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.