KevinS
KevinS

Reputation: 7875

How to update mongodb document and retrieve previous state atomically?

In Mongodb, is it possible to update a document and retrieve it's previous state in an atomic operation?

Upvotes: 1

Views: 355

Answers (1)

Gergo Erdosi
Gergo Erdosi

Reputation: 42048

You can use findAndModify. It has a new parameter which returns the original document if set to false (it's the default).

Optional. When true, returns the modified document rather than the original. The findAndModify() method ignores the new option for remove operations. The default is false.

Example:

db.people.findAndModify({
    query: { name: "Andy" },
    sort: { rating: 1 },
    update: { $inc: { score: 1 } },
    new: false
})

Upvotes: 3

Related Questions