vareen
vareen

Reputation: 53

How to concurrently read and update a field of mongodb from java

Let's take an example of facebook posts where multiple users give likes to a post. Now for some post currently database stores 10 likes and if two users liked that post concurrently then both will read 10 as current like and update 11 one by one but the correct value should be 12. How to achieve this using mongodb and java.

Upvotes: 1

Views: 554

Answers (1)

Ran Harari
Ran Harari

Reputation: 21

Check the operator $inc.

Here is a sample code from this link:

// connect to MongoDB server.
Mongo mongo = new Mongo("localhost", 27017);
DB database = mongo.getDB("mydb");
DBCollection collection = database.getCollection("testCollection");

// create a simple db object where counter value is 0
DBObject temp = new BasicDBObject("name", "someName").append("counter", 0);

// insert it into the collection
collection.insert(temp);

// create an increment query
DBObject modifier = new BasicDBObject("counter", 1);
DBObject incQuery = new BasicDBObject("$inc", modifier);

// create a search query
DBObject searchQuery = new BasicDBObject("name", "someName");

// increment a counter value atomically
WriteResult upRes = collection.update(searchQuery, incQuery);

Upvotes: 2

Related Questions