Reputation: 760
For example, for find and save document in MongoDB:
Article article1 = mongoOperation.findOne(new Query(Criteria.where("_id").is(1)), Article.class);
mongoOperation.save(article.setAttrA("A"));
Article article2 = mongoOperation.findOne(new Query(Criteria.where("_id").is(1)), Article.class);
mongoOperation.save(article.setAttrB("B"));
By default, _id is primary key so the document of article1 and article2 are the same.
Will it be possible to get a outdated document for article2 which attrA has not been set to A yet because in theoretically MongoDB does not follow the ACID properties.
Upvotes: 0
Views: 289
Reputation: 69663
Yes, the second query might return the same document before applying the save.
This is in fact quite likely if you are using an asynchronous API, a synchronous API with unsafe write concern or have a read-preference which prefers the secondary of a replica-set (which usually lacks behind a few seconds).
What you can do to detect and handle edit conflicts is to add a revision-id to each article which you increment by one on each edit. When you update an article, you use update instead of save, like this:
article.revision++;
writeResult = db.articles.update(
{ _id: article._id, revision: article.revision -1 },
article,
{ writeConcern: WriteConcern.ReplicaAcknowledged}
);
When someone edited the article in the meantime, the article with the old revision-id will be no longer in the database and you will get writeResult.nModified == 0
.
Upvotes: 2