Databases and Collections
Imagine you're organizing a huge library. You have different rooms (databases), and in each room, you have bookshelves (collections). Each bookshelf holds many books (documents). This is exactly how MongoDB organizes data!
What is a Database in MongoDB?
A database is a container for collections. In MongoDB, databases are created automatically when you first store data in them. Each database has its own permissions and can be stored in separate files on your system.
Think of a database as a separate project folder. You might have one database for your blog, another for your e-commerce site, and a third for your analytics.
What is a Collection?
A collection is a group of related documents. It's similar to a table in SQL databases, but unlike SQL tables, collections don't enforce a schema – documents in the same collection can have different fields.
| SQL Term | MongoDB Term |
|---|---|
| Database | Database |
| Table | Collection |
| Row | Document |
| Column | Field |
Working with Databases
Show all databases:
show dbsSwitch to a database (or create it):
use myblogIf `myblog` doesn't exist, MongoDB creates it when you first store data.
Check current database:
dbDrop (delete) current database:
db.dropDatabase()Working with Collections
Show all collections in current database:
show collectionsCreate a collection explicitly:
db.createCollection("users")Note: Collections are also created automatically when you insert the first document.
Drop a collection:
db.users.drop()Practical Example
<!-- Start mongosh and run these commands -->
> show dbsadmin 100kBconfig 100kBlocal 100kB
> use myblogswitched to db myblog
> dbmyblog
> db.createCollection("posts"){ ok: 1 }
> show collectionsposts
> db.posts.insertOne({ title: "First Post", content: "Hello World!" })
> show collections <!-- posts still there -->posts
> db.posts.drop()true
> show collections <!-- posts is gone -->
> db.dropDatabase(){ dropped: "myblog", ok: 1 }Two Minute Drill
- Databases contain collections – use `use dbname` to switch/create.
- Collections contain documents – like tables but without fixed schema.
- `show dbs` lists all databases, `show collections` lists collections in current DB.
- `db.dropDatabase()` deletes current database, `db.collection.drop()` deletes a collection.
- MongoDB creates databases and collections automatically when you first insert data.
Need more clarification?
Drop us an email at career@quipoinfotech.com
