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:


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


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:



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:



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:



Insert Collection

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

show collection