- Reference >
mongo
Shell 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 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 in a new ordinary collection. Theoptions
document contains the following fields:Field Type Description capped
Boolean Optional. Enables a capped collection. To create a capped collection, specify true
. If you specifytrue
, you must also set a maximum size in thesize
field.autoIndexId
Boolean Optional. If capped
istrue
, specifyfalse
to disable the automatic creation of an index on the_id
field. Before 2.2, the default value forautoIndexId
wasfalse
. See _id Fields and Indexes on Capped Collections for more information.size
number Optional. Specifies a maximum size in bytes for a capped collection. The size
field is required for capped collections. Ifcapped
is false, you can use this field to preallocate space for an ordinary collection.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 its maximumsize
before it reaches the maximum number of documents, MongoDB removes old documents. If you prefer to use this limit, ensure that thesize
limit, 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.