Automatic increment sequence in mongodb using java

Hi, I want _id auto- _id in mongodb using java. I am completely new to this. In the document, I found a solution as follows:

 db.counters.insert( { _id: "userid", seq: 0 } ) function getNextSequence(name) { var ret = db.counters.findAndModify( { query: { _id: name }, update: { $inc: { seq: 1 } }, new: true } ); return ret.seq; } db.users.insert( { _id: getNextSequence("userid"), name: "Sarah C." } ) 

Can anyone suggest how can I do this using java? I am completely new to this.

+4
source share
2 answers

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 }

+7
source
 DBCollection collection = database.getCollection("Table Name"); DBObject modifier = new BasicDBObject("counter", 1); DBObject incQuery = new BasicDBObject("$id", modifier); 
+3
source

All Articles