简体   繁体   English

如何在mongo db中自动增加非数字ID

[英]How to auto-increment non-numeric ID in mongo db

I want to auto-increment 'Project_ID' using mongo DB. 我想使用mongo DB自动增加“ Project_ID”。 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. 我需要将“ Project_ID”值设置为“ demo_1”,因此在尝试自动增加该值时使用该值,它显示错误:无法增加非数字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.

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 seq in a document keyed by Project_ID, in this case demo_1 . 您的代码正在尝试在由Project_ID键控的文档(本例为demo_1自动递增seq I ran your code although I got no errors, it is possible you don't have a "seed" record to findAndModify(). 尽管没有错误,但我运行了您的代码,很可能您没有“种子”记录来查找AndAndModify()。 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 . 另外:您将在每次调用getNextSequence连接和关闭连接。 That will be really slow. 那真的很慢。 I recommend you open the DB and capture the collection in main() and close it upon exit. 我建议您打开数据库并在main()捕获集合,然后在退出时将其关闭。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM