How to Create Collections in MongoDB

How to Create Collections in MongoDB

In This chapter , We will see how you can create collections in MongoDB, Actually in MongoDB you don’t need separate command to create collection as when you insert any document so mongodb automatically create collection if it is not exist. However there is a command to create mongodb collection.

Syntax

db.createCollection(name,options)

name : the name of collection

options : (optional) Configuration of collection like memory size , indexing etc.

Following is the list of options you can use.

FieldTypeDescription
cappedBoolean(Optional) If true, enables a capped collection. 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.
sizenumber(Optional) Specifies a maximum size in bytes for a capped collection. If capped is true, then you need to specify this field also.
maxnumber(Optional) Specifies 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

Below is the example how you can create collection with options parameters

Now I will show you how you can create your collection without using createCollection command

Hope you like my this topic so please share with your friends and visit us again

In Next Topic we will see how you can drop collections in Mongo DB

Leave a Reply
Your email address will not be published. *