i need to manage concurrency access for data updates in mongoDB. Example: two users a and b connect to my application. The user a has updated a data and the user b wants to update the same data that the user a has already updated, so i want the user b cannot update this data because is has already updated by the user a.
-
try use `compareAndSe` opreation – TongChen Jan 30 '19 at 10:10
-
@TongChen please can you give me an example for using compareAndSet – Jan 30 '19 at 10:17
-
Maybe have a look at the javax.persistence annotation @Version. https://stackoverflow.com/questions/10648515/using-version-in-spring-data-project – RichieK Jan 30 '19 at 18:19
1 Answers
if user A and user B only update one document and your can know the initial value and updated value try this code:
The code try to update the secret field,and we know the inital value is expertSecret
public void compareAndSet(String expertSecret, String targetSecret) {
// get a mongodb collection
MongoCollection<Document> collection = client.getDatabase(DATABASE).getCollection(COLLECTION);
BasicDBObject filter = new BasicDBObject();
filter.append("secret", expertSecret);
BasicDBObject update = new BasicDBObject();
update.append("secret", targetSecret);
collection.updateOne(filter, update);
}
If don't know initial value,how to do?
you can add a filed to representative operation,and before update check the filed.
If need to update more than one document,how to do? Multi-document transactions need mongo server to support,get more information from here
However, for situations that require atomicity for updates to multiple documents or consistency between reads to multiple documents, MongoDB provides the ability to perform multi-document transactions against replica sets. Multi-document transactions can be used across multiple operations, collections, databases, and documents. Multi-document transactions provide an “all-or-nothing” proposition.

- 1,414
- 1
- 11
- 21
-
thank you, I'll try to add a field and check it before doing an update. Is there a way to generate a sequence in mongodb with spring data that is auto incremented after each update or insert? – Jan 30 '19 at 12:46
-
Mongodb hava a `$inc` operator you can find the same opreation in `Spring Data` – TongChen Jan 30 '19 at 12:49