Create Collection and Capped Collection In MongoDB

In this tutorial we will learn how to Create Collection and Capped Collection In MongoDB. In our previous tutorial we learned to create database and use for data storage. MongoDB provides us create collection using method createCollection(). Command to create collection using following command.

Syntax :

>db.createCollection(name,option);

Example :

>db.createCollection(“users”);

Above example creates for you users collection now we will insert data in the users collection.

Insert data in collections :

>db.users.insert("username":"admin");

For check collection is created on database use command 

>show collections

Result :

users

To fetch data which we had stored in collection using this command

>db.users.find({})

. it will return all record inserted in to the collection. find() method is used to fetch data from collection.

One More Type to create collection for fix size which is Capped Collection

In you need to create fixed size parameter so you need to define capped parameter in optional field and also define size and max limit of document. For fixed size collection need to know about following parameter.

Capped (Boolean) If it is true means capped collection is enabled. If capped enables make sure your size parameter has to be defined.
size(number) If capped true then need to define size.
max(number) Specify the maximum number of document allow in capped collection.

Now we will create capped collection in MongoDB. Using following command.

>db.createCollection("x_users",{ capped:true ,size:412506,max:10000})

When you run command then you will get ok : 1 message like :

{ "ok" : 1 }

Now your created collection is capped collection means fixed size collection.