Contents
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:
Parameter | Type | Description |
---|---|---|
name | string | The name of the collection to create. |
options | document | Optional. 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:
Field | Type | Description |
---|---|---|
capped | Boolean | (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. |
autoIndexID | Boolean | (Optional) If true, automatically create index on _id field.s Default value is false. |
size | number | (Optional) Specifies a maximum size in bytes for a capped collection. If If capped is true, then you need to specify this field also. |
max | number | (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 :
1 2 3 4 5 6 7 8 |
[user@devops-team $] mongo MongoDB shell version: 2.0.4 connecting to: test > > > use devops-teamDB switched to db devops-teamDB > |
- 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
1 |
> show collections<br>mycollection<br>system.indexes<br>> |
Following example shows the syntax of createCollection() method with few important options:
1 |
>db.createCollection("mycollection2", { capped : true, autoIndexID : true, size : 6142800, max : 10000 } )<br>{ "ok" : 1 }<br>><br>> show collections<br>mycollection2<br>mycollection<br>system.indexes<br>> |
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 🙂