MongoDB Collections
A collection in MongoDB is similar to a table in RDBMS. MongoDB collections do not enforce schemas. Each MongoDB collection can have multiple documents. A document is equilant to row in a table in RDBMS.
To create a collection, use the db.createCollection()
command.
The following creates a new employees
collection in the current database, which is humanResourceDB
database created in the previous chapter.
![](../../Content/images/mongodb/create-collection1.png)
Above, the employees
collection is created using the creatCollection()
method.
It returns an object { ok: 1 }
, which indicates the collection was created successfully.
As mentioned above, a single database can have multiple collections. The following creates multiple collections.
![](../../Content/images/mongodb/create-collection2.png)
Use the show collections
commands to list all the collections in a database.
![](../../Content/images/mongodb/create-collection3.png)
To delete a collection, use the db.<collection-name>.drop()
method.
![](../../Content/images/mongodb/create-collection4.png)
Create Collection in MongoDB Compass
To create a new collection using MongoDB Compass, connect compass to your server and select the database.
Click on the "Create Collection" button to create a new collection, as shown below.
![](../../Content/images/mongodb/compass5.png)
Enter the name of a collection, check appropriate checkbox and click on the Create Collection
button to create it.
![](../../Content/images/mongodb/create-collection-compass.png)
Thus, you can create a new collection using MongoDB Shell mongosh or MongoDB Compass.