Understanding MongoDB Collections: A Flexible Data Structure

Learn about MongoDB collections, which are equivalent to tables in relational databases. Discover how MongoDB collections provide flexibility in data storage by not enforcing strict schemas. Explore the process of creating and working with collections in MongoDB.



MongoDB Collections

In MongoDB, a collection is like a table in an RDBMS. Collections do not enforce schemas, and each collection can have multiple documents, similar to rows in a table.

Create a Collection

Use the db.createCollection() command to create a new collection. For example, to create an employees collection in the humanResourceDB database:

Create Collection

db.createCollection("employees")

The command returns { ok: 1 } if the collection is created successfully.

Create Multiple Collections

To create multiple collections, simply repeat the db.createCollection() command with different collection names.

Create Multiple Collections

db.createCollection("employees")
db.createCollection("departments")
db.createCollection("salaries")

Show Collections

Use the show collections command to list all collections in the current database:

Show Collections

show collections

Delete a Collection

To delete a collection, use the db..drop() method:

Delete Collection

db.employees.drop()

Create a Collection in MongoDB Compass

To create a new collection using MongoDB Compass, connect to your server, select the database, and click on the Create Collection button.

Create Collection in MongoDB Compass

Click on "Create Collection" button
Enter collection name
Click "Create Collection"

Enter the collection name, adjust settings if needed, and click Create Collection to finalize.