Working with Databases and Collections

Learn how to create, drop, and switch between databases. Explore how to create and manage collections within a database.


MongoDB Essentials: Creating Databases

Creating Databases

In MongoDB, a database is a container for collections. Collections, in turn, are containers for documents (similar to tables in relational databases). Before you can store any data, you need to create a database. This section will guide you through the different methods of creating databases in MongoDB.

Implicit Database Creation

MongoDB databases are created implicitly. This means that you don't explicitly need to issue a CREATE DATABASE command. The database is created automatically when you first store data into it. The database is physically created on disk when you first write data to a collection.

To implicitly create a database, you can simply switch to a database that doesn't exist and insert a document into a collection within that database.

 use myNewDatabase  // Switches to (or creates) the 'myNewDatabase' database

            db.myNewCollection.insertOne({ name: "Example Document" }) // Inserts a document, triggering database creation 

In this example, if myNewDatabase doesn't already exist, MongoDB will create it when the insertOne() method is called on the myNewCollection collection.

Explicit Database Use (Switching to a Database)

The use command is used to select (or switch to) a particular database. This command does *not* create the database immediately on its own. It only sets the current database context for subsequent operations.

 use anotherNewDatabase 

After running this command, any operations you perform on the db object will be executed against the anotherNewDatabase database. The database file itself will only be created when you actually write data to it.

Checking Existing Databases

You can check which databases exist using the show dbs command in the mongo shell.

 show dbs 

This command will list all the databases that MongoDB knows about. Note that a database might not appear in this list if it doesn't contain any data.

Database Names

MongoDB enforces certain restrictions on database names:

  • Database names must be valid UTF-8 strings.
  • Database names should not contain spaces, forward slashes (/), backslashes (\), periods (.), double quotes ("), asterisks (*), dollar signs ($).
  • Database names should be all lowercase.
  • Database names cannot be an empty string.
  • Database names are case-sensitive, even though it is advised that names are lower case only
  • Database names cannot exceed 64 bytes.

Learn how to create new databases in MongoDB using different methods

As shown above MongoDB uses implicit database creation to create databases. By writing data to a collection within a non-existent database, it triggers its creation. Also the use command switches or selects the current database which only creates the database file once data is written