Using Create a field of automatic incremental sequence, first you should create a collection using the mongoDB shell, and the collection should be like this:
db.counters.insert( { _id: "userid", seq: 0 })
So, you get counters collections that contain a field of type _id,seq , now create the getNextSequence function in java, and this function has the userid parameter as a string, so getNextSequence works like this:
public static Object getNextSequence(String name) throws Exception{ MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); // Now connect to your databases DB db = mongoClient.getDB("demo"); DBCollection collection = db.getCollection("counters"); BasicDBObject find = new BasicDBObject(); find.put("_id", name); BasicDBObject update = new BasicDBObject(); update.put("$inc", new BasicDBObject("seq", 1)); DBObject obj = collection.findAndModify(find, update); return obj.get("seq");
}
The above function returns seq count and uses this function in the main method as:
public static void main(String[] args) throws Exception { MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); // Now connect to your databases DB db = mongoClient.getDB("demo"); DBCollection collection = db.getCollection("counters"); BasicDBObject document = new BasicDBObject(); document.put("_id", getNextSequence("userid")); document.put("name","Sarah C."); collection.insert(document); // insert first doc document.put("_id", getNextSequence("userid")); document.put("name", "Bob D."); collection.insert(document); // insert second doc }
Now, in counters collection contains three documents that contain a name like Sarah C. and Bob D. respectively, and one default document, which we manually insert for the first time, and increase seq , like this { "_id" : "userid", "seq" : 2 }