Creating a mongodb capped collection in java

后端 未结 2 1611
鱼传尺愫
鱼传尺愫 2021-02-10 22:58

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 =         


        
相关标签:
2条回答
  • 2021-02-10 23:44

    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.

    0 讨论(0)
  • 2021-02-10 23:50

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题