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.
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.
Use the show collections
commands to list all the collections in a database.
To delete a collection, use the db.<collection-name>.drop()
method.
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.
Enter the name of a collection, check appropriate checkbox and click on the Create Collection
button to create it.
Thus, you can create a new collection using MongoDB Shell mongosh or MongoDB Compass.