Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a mongodb capped collection in java

Tags:

mongodb-java

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 ?????? */
    }
}
like image 441
Lee Jensen Avatar asked Dec 08 '22 23:12

Lee Jensen


1 Answers

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);
    }
}
like image 172
Lee Jensen Avatar answered Jan 15 '23 19:01

Lee Jensen