MongoDB: Create Collection

How to Create a Collection in MongoDB?

Collection in Mongo DB can be defined as the collection of Documents. Collection can be considered as what we call Table in RDBMS ( Relational Database Management System). Like table in RDBMS contains different attributes and values inside that attributes, in the same way, we have collections in MongoDB, that contain groups of documents. You can follow the syntax below to create a Collection:

Syntax

1) When you want to create an empty collection, that contains no values. You can use the below syntax to create a Collection:

db.createCollection('Collection_Name')

NOTE: The Collection_Name in MongoDB must fulfill the following criteria:

  • It is always enclosed between single inverted commas(' ').
  • The Name never begins with numeric values or special characters except for Underscore(_).
  • The maximum length of the command should take no more than 120 Bytes. 

2) When you want to create a Collection at the time of inserting documents into the same collection:

db.Collection_Name.InsertOne({Document})

Example

1) We have a Database named MyDB. A collection named MyfirstCollection needs to be created into MyDB. On the other hand, you don't want to insert values into a similar collection. However, to create MyfirstCollection follow the code below:

 db.createCollection('MyfirstCollection')

Output:

create collection

NOTE: Show Collections Command in MongoDB is used to see all the existing collections in the current database.

2) Now, let's try to create another collection named MysecondCollection. But this time, we will try to insert a document too into that collection. Follow the step below for the same:

db.MysecondCollection.insertOne({Name:'Ashi',Salary:15000})

Output

Insert Collection

Also, executing the show connections command will show you that the collection is actually created:

show collection