MongoDB Java Driver creating Database and Collection

混江龙づ霸主 提交于 2019-12-05 18:41:08

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/

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