user2775185
user2775185

Reputation: 1207

MongoDB Java Driver creating Database and Collection

i was testing how to create database and collection mongo java driver.

  MongoClient client = new MongoClient("localhost",27017);
        DB db = client.getDB("ow");
        DBCollection collection = db.getCollection("documents");
        collection.save(new BasicDBObject("_id",1));
        collection.remove(new BasicDBObject("_id",1));
        boolean result = db.collectionExists("documents");
        assertTrue(result);
        assertNotNull(collection);
        client.close();

I would prefer to use createCollection method on the DB object, but found that it does not create database / collection unless the first document is inserted.

My question is is this understanding correct ? Is above code correct was of creating collection or database.

Upvotes: 3

Views: 9726

Answers (1)

BatScream
BatScream

Reputation: 19700

prefer to use createCollection method on the DB object, but found that it does not create database / collection unless the first document is inserted.

MongoDB creates a collection implicitly when the first document is saved into a collection. The createCollection() method explicitly creates a collection only and only if an options object is passed to it as an argument.

Now this makes sense. The options parameter can take in one or more arguments to decide the characteristics of the collection we want to create such as capped,autoIndexId,size,usePowerOf2Sizes,max no. of documents.

If we do not specify any of these options, the default behavior would take precedence, i.e create a collection lazily whenever the first insert is made, with default settings.

So if we want a collection whose characteristics we are going to define, then we can pass these characteristics as a DBObject to the createCollections() method and our collection would be created. Below is an example of how to pass the options.

BasicDBObject options =  new BasicDBObject();
options.put("size", 12121212);
db.createCollection("hello", options);

Is above code correct was of creating collection or database.

Yes. It allows mongodb to apply the default configuration for your collection. Unless you want to set the max,size,autoIndexId,capped,usePowerOf2Sizes properties for your new collection, this is fine.

Refer: http://docs.mongodb.org/manual/reference/method/db.createCollection/

Upvotes: 5

Related Questions