Loading

Quipoin Menu

Learn • Practice • Grow

mongodb / Databases and Collections
tutorial

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 TermMongoDB Term
DatabaseDatabase
TableCollection
RowDocument
ColumnField

Working with Databases

Show all databases:
show dbs

Switch to a database (or create it):
use myblog

If `myblog` doesn't exist, MongoDB creates it when you first store data.

Check current database:
db

Drop (delete) current database:
db.dropDatabase()

Working with Collections

Show all collections in current database:
show collections

Create 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 dbs
admin 100kB
config 100kB
local 100kB

> use myblog
switched to db myblog

> db
myblog

> db.createCollection("posts")
{ ok: 1 }

> show collections
posts

> 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