Spriha Srivastava
Spriha Srivastava

Reputation: 65

How to auto-increment non-numeric ID in mongo db

I want to auto-increment 'Project_ID' using mongo DB. I need to put 'Project_ID' value as 'demo_1', so using this value when I trying to auto-increment this value, it showing error: can not increment non numeric id.

public static Object getNextSequence(String Project_ID) throws Exception{
           // MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
            // Now connect to your databases
           // DB db = mongoClient.getDB("demo");
            DB db=ConnectToDB.getConnection();
              Properties prop = new Properties();
              InputStream input = null;
                input = Demo.class.getClassLoader().getResourceAsStream("config.properties");
                prop.load(input);
                String col=prop.getProperty("COLLECTION_DEMO");
            DBCollection collection = db.getCollection("counters");
            BasicDBObject find = new BasicDBObject();
            find.put("_id", Project_ID);
            BasicDBObject update = new BasicDBObject();
            update.put("$inc", new BasicDBObject("seq", 1));
            DBObject obj =  collection.findAndModify(find, update);
            db.getMongo().close();
            return obj.get("seq");
        }
Please let me know what is the issue there or what is the possible way to achieve this. Thanks.

Upvotes: 0

Views: 362

Answers (1)

Buzz Moschetti
Buzz Moschetti

Reputation: 7578

Your explanation of what you're trying to autoincrement does not match the code, never mind the error. You're code is trying to autoincrement seqin a document keyed by Project_ID, in this case demo_1. I ran your code although I got no errors, it is possible you don't have a "seed" record to findAndModify(). Try running this to create your seed:

db.counters.drop();
db.counters.insert({_id: "demo_1", seq: NumberInt("0")});

then run your code. Also: You are connecting and closing the connection with each call to getNextSequence. That will be really slow. I recommend you open the DB and capture the collection in main()and close it upon exit.

Upvotes: 1

Related Questions