- 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. This is also used to pre-allocate space for an ordinary collection.
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. If cappedistrue, specifyfalseto 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.sizenumber Optional. Specifies a maximum size in bytes for a capped collection. The sizefield is required for capped collections. Ifcappedis false, you can use this field to preallocate space for an ordinary collection.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.
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.
The following command simply pre-allocates a 2-gigabyte, uncapped
collection named people:
This command provides a wrapper around the database command
create. See Capped Collections for more
information about capped collections.