Pages - Menu

Thursday, June 9, 2016

The createCollection() Method - To Create Collection

db.createCollection(name, options) is used to create collection explicitly.

This method is used primarily for creating new capped collections, because MongoDB creates a collection implicitly when the collection is first referenced in a command.

this command is also used to pre-allocate space for an ordinary collection.

The db.createCollection(name, options) method has the following prototype form:

db.createCollection(<name>, { capped: <boolean>,
                              autoIndexId: <boolean>,
                              size: <number>,
                              max: <number>,
                              storageEngine: <document> } )


The db.createCollection(name, options) method has the following parameters:

Parameter Type Description
name string The name of the collection to create.
options document Optional. Configuration options for creating a capped collection or for preallocating space in a new collection.

The options document creates a capped collection or preallocates space for new ordinary collection.
The options document contains the following fields:

Field Type Description
capped boolean Optional. To create a capped collection, specify true. If you specifytrue, you must also set a maximum size in the size field.
autoIndexId boolean Optional. Specify false to disable the automatic creation of an index on the _id field.

NOTE:
For replica sets, all collections must have autoIndexId set totrue.
size number Optional. Specify a maximum size in bytes for a capped collection. Once a capped collection reaches its maximum size, MongoDB removes the older documents to make space for the new documents. The size field is required for capped collections and ignored for other collections.
max number Optional. The maximum number of documents allowed in the capped collection. The size limit takes precedence over this limit. If a capped collection reaches the size limit before it reaches the maximum number of documents, MongoDB removes old documents. If you prefer to use themax limit, ensure that the size limit, which is required for a capped collection, is sufficient to contain the maximum number of documents.
usePowerOf2Sizes boolean Optional. Available for the MMAPv1 storage engine only.
noPadding boolean Optional. Available for the MMAPv1 storage engine only.
Defaults to false.
storageEngine document Optional. Available for the WiredTiger storage engine only.

No comments:

Post a Comment