How to create Collection database in MongoDB

by Ismail.EL
0 comment

How to create Collection database in MongoDB

1. Introduction :

In this guide, i will show you how create Collection in MongoDB.

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

Syntax :
Basic syntax of createCollection() command is as follows:  db.createCollection(name, options)
In the command, name is name of collection to be created. Options is a document and used to specify configuration of collection.

The db.createCollection() method has the following parameters:

namestringThe name of the collection to create.
optionsdocumentOptional. Configuration options for creating a capped collection or for preallocating space in a new collection.

Options parameter is optional, so you need to specify only name of the collection. Following is the list of options you can use:

cappedBoolean(Optional) If true, enables a capped collection. Capped collection is a collection fixed size collecction that automatically overwrites its oldest entries when it reaches its maximum size. If you specify true, you need to specify size parameter also.
autoIndexIDBoolean(Optional) If true, automatically create index on _id field.s Default value is false.
sizenumber(Optional) Specifies a maximum size in bytes for a capped collection. If 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.

2. Connect to database and create Collection :

  • connect to database :

First we will select our database we want to create a collection :

  • create collection :

The following command allows you to create a new collection in database devops-teamDB :> db.createCollection(“mycollection”)
{ “ok” : 1 }

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

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

3. Conclusion

In this post, i have explained How to drop database in MongoDB.
If you have any questions or feedback, feel free to leave a comment.
As always, if you found this post useful, then click like and share it 🙂

21150cookie-checkHow to create Collection database in MongoDB

Related Posts

Leave a Comment