Create Collection in mongoDB

A collection is the group of mongoDB documents. mongoDB stores document in the collection. mongoDB collection doesn’t follow the schema concept, therefore, a document can have a different field within a collection.

db.createCollection(name,option) is used to create the collection.

Syntax


db.createCollection(<name>,<option>)


Name parameter is the string type ,here we put the name of the collection.
Option parameter is the document which specifies options about memory size and indexing etc. Option parameter is optional, so you need to specify the only name of the collection. Following is the list of the options you can use.


Field

Type

Description


capped

Boolean

Capped collection is a fixed size collection that automatically overwrites its oldest entries when it reaches its maximum size. If you specify true, you need to specify size parameter also.


autoIndexID


Boolean

If true automatically creates an index on _id field.s Default


size

number

If capped is true it specifies a maximum size in bytes for a capped collection, and then you need to specify this field also.


max


number

This allows the maximum number of documents allowed in the capped collection.


While inserting the document, MongoDB first checks size field of capped collection, then it checks max field.

Example

Following I am trying to write basic syntax for createCollection() method.


>use test
switched to db test
>db.createCollection("mongocollection")

Result
{ "ok" : 1 }


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


>show collections

Result
mongocollection
system.indexes


Following example shows the syntax of createCollection() method with few important options:


>db.createCollection("mongocollection ", { capped : true, autoIndexID : true, size : 6142800, max : 10000 } )

Result
{ "ok" : 1 }


In mongodb you don't need to create collection. MongoDB creates collection automatically, when you insert some document.


>db.Codefari.insert({"name" : "Codefari"})
>show collections

Result
mongocollection
system.indexes
codefari



You can see collection Codefari is created.