Creating a mongodb capped collection in java

I want to create a limited 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 ?????? */ } } 
+4
mongodb-java
source share
2 answers

Use the DB.createCollection operation, and then specify DBObject with capped as the parameter. You can then specify the size and max to control the byte size and the maximum number of documents. The MongoDB website has a tutorial on private collections that explains all the options, but there is no 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); } } 
+13
source share

With the more recent java mongo driver (i.e. 3.4), the creation should change a bit:

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

Note that createCollection does not return any value.

0
source share

All Articles