Creating a mongodb capped collection in java

萝らか妹 提交于 2019-12-04 13:43:37

问题


I want to create a capped collection from Java code. I found the syntax for creating it through JavaScript, but could not find an example for Java.

Mongo mongo = new Mongo("127.0.0.1");
DB db = mongo.getDB("mydbid");

DBCollection collection;
if (db.collectionExists("mycollection")) {
        collection = db.getCollection("mycollection");
    } else {
        collection = /* ????? Create the collection ?????? */
    }
}

回答1:


Use the DB.createCollection operation and then specify a DBObject that has capped as a parameter. You can then specify size and max in order to control the byte size and the maximum number of documents. The MongoDB site has a tutorial on capped collections that explains all the options, but is missing an example for each driver.

Mongo mongo = new Mongo("127.0.0.1");
DB db = mongo.getDB("mydbid");

DBCollection collection;
if (db.collectionExists("mycollection")) {
        collection = db.getCollection("mycollection");
    } else {
        DBObject options = BasicDBObjectBuilder.start().add("capped", true).add("size", 2000000000l).get();
        collection = db.createCollection("mycollection", options);
    }
}



回答2:


With more recent java mongo driver (ie 3.4) the creation should slightly change:

CreateCollectionOptions opts = new CreateCollectionOptions().capped(true).sizeInBytes(1024*1024);
database.createCollection("test", opts);

Please, notice that the createCollection is not returning any value.



来源:https://stackoverflow.com/questions/11229237/creating-a-mongodb-capped-collection-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!