Hi I want to auto increment _id
in mongodb using java. I am completely new to this. In the document I found the solution like this:
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 any one suggest how do I do this using java ? I am completely new to this.
Using Create an Auto-Incrementing Sequence Field first you should create collection using mongoDB shell and collection should be as :
db.counters.insert(
{
_id: "userid",
seq: 0
})
So you get counters
collections which contains field like _id,seq
, now create getNextSequence
function in java and this function having parameter userid
as string so getNextSequence
function 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 return seq
count and used this function in main
method as like :
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 which contains name
as Sarah C. and Bob D.
respectively and one default documents which we inserted manually at first time and it increment seq
like this { "_id" : "userid", "seq" : 2 }
DBCollection collection = database.getCollection("Table Name");
DBObject modifier = new BasicDBObject("counter", 1);
DBObject incQuery = new BasicDBObject("$id", modifier);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With