MongoDB - Create Collection

createCollection() method
MongoDB db.createCollection(name, parameters) is used to create a collection.
Syntax
The basic syntax of the createCollection() command is as follows:
db.createCollection(name, options)
In the name command , this is the name of the collection to be created. Options is a document that is used to specify the collection's configuration.
parameter | A type | Description |
---|---|---|
title | line | The name of the collection to be created |
Options | Document | (Optional) Specify options for memory and indexing |
The options parameter is optional, so only the name of the collection needs to be specified. Following is the list of options that you can use −
field | A type | Description |
---|---|---|
limited | logical | (Optional) If set to true, includes the limited collection. A limited collection is a fixed-size collection that automatically overwrites its oldest entries when it reaches its maximum size. If you specify true, you also need to specify a size parameter. |
autoIndexId | logical | (Optional) If set to true, automatically create an index on the _id field. The default value is false. |
the size | number | (Optional) Specifies the maximum size in bytes for a limited collection. If capped is true, then you also need to specify this field. |
Maximum | number | (Optional) Specifies the maximum number of documents allowed in a limited collection. |
When inserting a document, MongoDB first checks the size field of the constrained collection and then checks the max field.
Examples
The basic syntax of the createCollection() method without options is as follows:
> use test switched to db test > db . createCollection ( "mycollection" ) { "ok" : 1 } >
You can check the created collection with the show collection command .
> show collections mycollection system . indexes
The following example shows the syntax of the createCollection() method with several important parameters:
> db . createCollection ( "mycol" , { capped : true , autoIndexId : true , size : 6142800 , max : 10000 } ) { "ok" : 1 } >
In MongoDB, you don't need to create a collection. MongoDB creates a collection automatically when you insert any document.