Auto increment sequence in mongodb using java

后端 未结 2 483
北恋
北恋 2020-12-16 20:02

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         


        
相关标签:
2条回答
  • 2020-12-16 20:18
    DBCollection collection = database.getCollection("Table Name");
    
    DBObject modifier = new BasicDBObject("counter", 1);
    DBObject incQuery = new BasicDBObject("$id", modifier);
    
    0 讨论(0)
  • 2020-12-16 20:33

    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 }

    0 讨论(0)
提交回复
热议问题