What is the best way to read then update in mongodb?

Viewed 892

I need to read a document from a collection, read its value, then if the value is <40 I need to increment the value.

Here is my current solution

let promise = db.collection('transactions').findOne(
        { _id: 'myid' }
    ).then(doc => {
        if (doc.count < 40) {
            ///update & increment doc.count
        }
        else {
            //do not increment
        }
    });

Does findOneAndModify allow for reading the document before modifying?

2 Answers

You can encode this condition within the query and do a simple update:

db.collection('transactions').updateOne(
    {_id: 'id', count: {$lt: 40}},
    {$inc: {count: 1}}
)

If you need to get the document (before or after the modification) simply use findAndModify:

db.collection('transactions').findAndModify({
    query: {_id: 'id', count: {$lt: 40}},
    update: {$inc: {count: 1}},
    new: trueIfYouWantToGetTheModifiedVersion
})
Related