简体   繁体   中英

manage concurrency access mongoDB

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM