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.

Create Collection

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.

Create Multiple Collections

Use the show collections commands to list all the collections in a database.

Show Collections

To delete a collection, use the db.<collection-name>.drop() method.

Delete Collection

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.

MongoDB Compass - Collections

Enter the name of a collection, check appropriate checkbox and click on the Create Collection button to create it.

MongoDB Compass - Collections

Thus, you can create a new collection using MongoDB Shell mongosh or MongoDB Compass.

Want to check how much you know MongoDB?