MongoDB Tutorial - MongoDB Create Collection








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

Syntax

The following command shows how to create a collection with createCollection() command.

db.createCollection(name, options)

name is name of collection. Options, which is Optional, is a document and used to set up the collection.

The following table shows the list of options we can use:

FieldTypeDescription
capped Boolean Optional. true value enables a capped collection. Capped collection is a fix-sized collection that overwrites its oldest entries when it reaches its maximum size. true value requires you to specify size parameter.
autoIndexID Boolean Optional, true value creates index on _id field. Default value is false.
size number Optional. Set a maximum size in bytes for a capped collection.
max number Optional. Set the maximum number of documents allowed in the capped collection.




Example

The following code creates a collection with default settings.

>use test
switched to db test
>db.createCollection("mycollection")
{ "ok" : 1 }
>

To check the created collection, use the following command:

>show collections
mycollection
system.indexes

The following example shows how to use createCollection() method with options:

>db.createCollection("mycol", { capped : true, autoIndexID : true, size : 2800, max : 10000 } )
{ "ok" : 1 }
>

MongoDB can create collection automatically when inserting some document.

>db.tutorialspoint.insert({"name" : "java2s"})
>show collections
mycol
mycollection
system.indexes
java2s
>