Home >>MongoDB Tutorial >MongoDB Create Collection

MongoDB Create Collection

How to Create Collection using MongoDB

We will see how to create a collection using MongoDB in this chapter.

The createCollection() Method

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


Basic syntax of createCollection() command is as follows −

db.createCollection(name, options)

The name in the command is the name of the collection that will be created. Options is a document which is used to define the collection configuration.

Parameter Type Description
Name String Collection name to be created
Options Document (Optional) Specify memory size and indexing options

The Options parameter is optional, so only the collection name needs to be specified. The list of options you can use is below:

Field Type Description
capped Boolean (Optional) Allows a capped collection if true. Capped is a collection of fixed sizes that, when it reaches its maximum size, automatically overwrites its oldest entries. If true is defined, you will need to specify the size parameter.
autoIndexId Boolean (Optional) If true, create an index automatically in the _Id fields The default value is false.
size number (Optional) Determines the maximum size for a capped array in bytes. If the capped field is true, then this field must also be defined.
max number (Optional) Determines the maximum number of documents in the capped collection that are allowed.

MongoDB first checks the size of the capped collection field when inserting the document, and then checks the max field.


Basic syntax of createCollection() method without options is as follows −

>use test
switched to db test
{ "ok" : 1 }

You can check the created collection by using the command show collections.

>show collections

The following example shows the syntax of createCollection() method with few important options −

>db.createCollection("mycol", { capped : true, autoIndexID : true, size : 6142800, max : 10000 } ){
"ok" : 0,
"errmsg" : "BSON field 'create.autoIndexID' is an unknown field.",
"code" : 40415,
"codeName" : "Location40415"

You don't need to create a collection for MongoDB. MongoDB will automatically create a collection when you insert a document.

>db.phptpoint.insert({"name" : " phptpoint"}),
WriteResult({ "nInserted" : 1 })
>show collections

No Sidebar ads