- Reference >
mongoShell Methods >- Database Methods >
- db.createCollection()
db.createCollection()¶
On this page
Definition¶
-
db.createCollection(name, options)¶ Creates a new collection explicitly.
Because MongoDB creates a collection implicitly when the collection is first referenced in a command, this method is used primarily for creating new capped collections.
db.createCollection()is a wrapper around the database commandcreate.The
db.createCollection()method has the following prototype form:The
db.createCollection()method has the following parameters:Parameter Type Description namestring The name of the collection to create. optionsdocument Optional. Configuration options for creating a capped collection or for preallocating space in a new collection. The
optionsdocument creates a capped collection or preallocates space in a new ordinary collection. Theoptionsdocument contains the following fields:Field Type Description cappedBoolean Optional. Enables a capped collection. To create a capped collection, specify true. If you specifytrue, you must also set a maximum size in thesizefield.autoIndexIdBoolean Optional. Specify
falseto disable the automatic creation of an index on the_idfield. Before 2.2, the default value forautoIndexIdwasfalse. See _id Fields and Indexes on Capped Collections for more information.Important
For replica sets, all collections must have
autoIndexIdset totrue.sizenumber Optional. Specifies a maximum size in bytes for a capped collection. The sizefield is required for capped collections, and ignored for other collections.maxnumber Optional. The maximum number of documents allowed in the capped collection. The sizelimit takes precedence over this limit. If a capped collection reaches its maximumsizebefore it reaches the maximum number of documents, MongoDB removes old documents. If you prefer to use this limit, ensure that thesizelimit, which is required, is sufficient to contain the documents limit.usePowerOf2Sizesboolean Optional. Set to
falseto disable theusePowerOf2Sizesallocation strategy for this collection. Defaults totrueunless thenewCollectionsUsePowerOf2Sizesparameter is set tofalse.New in version 2.6:
usePowerOf2Sizesbecame an option todb.createCollection()whenusePowerOf2Sizesbecame the default allocation strategy for all new collections.
Example¶
The following example creates a capped collection. Capped collections have maximum size or document counts that prevent them from growing beyond maximum thresholds. All capped collections must specify a maximum size and may also specify a maximum document count. MongoDB removes older documents if a collection reaches the maximum size limit before it reaches the maximum document count. Consider the following example:
This command creates a collection named log with a maximum size of 5
megabytes and a maximum of 5000 documents.
See Capped Collections for more information about capped collections.