Lesson 5 +10 XP

Create a Database

Create a Database

In MongoDB, a database holds one or more collections. Databases and collections are created lazily - they only exist once they actually contain data.

Check the current database

When you connect, type db to see which database you're using:

db

With a standard Atlas connection string you connect to myFirstDatabase by default.

List all databases

show dbs

Here's the catch: an empty database is not listed. If a database has no collections with data, show dbs won't show it - to MongoDB it essentially doesn't exist yet.

Switch to or create a database

Use the use command to switch to an existing database, or to create a new one:

use blog

When is the database really created?

A database only becomes real once it contains data. So after use blog, the blog database still doesn't exist in show dbs until you add a collection and insert a document.

TL;DR

  • db shows the current database.
  • show dbs lists databases that contain data.
  • use <name> switches to or creates a database.
  • Empty databases don't appear in show dbs until they have content.