Back to all posts

MongoDB Create Database: mongosh, Atlas, Compass, Docker, and DbSchema

For developers creating their first MongoDB database, in the mongosh shell or in a GUI such as Atlas, Compass or DbSchema.

On this page

MongoDB has no CREATE DATABASE statement. In mongosh[1], the MongoDB shell, switch to the name you want and insert a document. MongoDB creates the database, and the collection that holds the document, when it stores that document[2]:

use flights
db.flightData.insertOne({ departureAirport: "LHR", arrivalAirport: "TXL", distance: 950 })

use alone stores nothing, so show dbs, the command that lists databases, shows flights only after the insert. Atlas, Compass and DbSchema also create a database together with its first collection.

Lesson 2 of the MongoDB course:

  1. Introduction to MongoDB
  2. Installation & Database Creation (You are here).
  3. CRUD operations in MongoDB
  4. Embedded Documents and Arrays
  5. Validation rules that enforce structure in MongoDB
  6. Visualize MongoDB Relationships (Embedded vs Referenced)
  7. What Is an Index in MongoDB?
  8. Aggregation Pipeline Explained

Create a MongoDB database in mongosh

The output below is copied from MongoDB 8.2 and mongosh 2.8. Started with no arguments, mongosh connects to the server on your own machine, with test as the current database.

Install MongoDB Server

Skip this step if a server already runs, or if you'd rather use Docker. MongoDB's installation tutorial[3] has the commands for each system.

On Windows, run the MSI installer of MongoDB Community Server and select Install MongoD as a Service, so that the server starts with Windows. The installer leaves out mongosh, so install the MongoDB Shell[1] separately. On macOS, the mongodb-community formula from MongoDB's Homebrew tap installs both, and so does the mongodb-org package on Ubuntu.

Run mongosh when the install finishes. The prompt test> means that mongosh has connected to the server.

Switch to a new database with use

show dbs lists the databases that the server has stored. A new server has three, for MongoDB's own use:

show dbs
admin    8.00 KiB
config  12.00 KiB
local    8.00 KiB

use makes flights the current database of your session:

use flights
switched to db flights

The prompt changes to flights>, and db now refers to flights. Run show dbs again: the list still has the same three databases. use has stored nothing on the server.

Insert the first document

insertOne stores one document in a collection. If the collection and its database don't exist yet, MongoDB creates both to hold the document[2]:

db.flightData.insertOne({ departureAirport: "LHR", arrivalAirport: "TXL", distance: 950 })
{
  acknowledged: true,
  insertedId: ObjectId('6af4fbcfc1dd93b0a044ba89')
}

The document had no _id field, its unique key, so MongoDB added one with a new ObjectId. Now show dbs lists flights:

show dbs
admin     8.00 KiB
config   12.00 KiB
flights   8.00 KiB
local     8.00 KiB

find reads the document back from the new collection:

db.flightData.find()
[
  {
    _id: ObjectId('6af4fbcfc1dd93b0a044ba89'),
    departureAirport: 'LHR',
    arrivalAirport: 'TXL',
    distance: 950
  }
]

What you can call a MongoDB database

The name has to meet the server's naming restrictions[5], and Windows forbids more characters than Linux and macOS:

RestrictionMongoDB database names
Lengthnot empty, and less than 64 bytes
Forbidden on Linux and macOS/\. "$ and the null character
Forbidden on Windows/\. "$*<>:?, the vertical bar and the null character
CasesalesData and SalesData cannot both exist

mongosh accepts some invalid names in use, and the server rejects them at the first write. The namespace in the error is the database name and the collection name, joined by a dot:

use my$db
db.flightData.insertOne({ departureAirport: "LHR" })
Uncaught MongoServerError[InvalidNamespace]: Invalid namespace: my$db.flightData

Why an empty MongoDB database does not persist

A database exists on the server only while it holds a collection. The collection can be empty: db.createCollection creates it, and its database, without a document:

use airports
db.createCollection("airportData")
show dbs
{ ok: 1 }
admin      8.00 KiB
airports   8.00 KiB
config    12.00 KiB
flights    8.00 KiB
local      8.00 KiB

Drop the last collection, and the database goes with it:

db.airportData.drop()
show dbs
true
admin     8.00 KiB
config   12.00 KiB
flights   8.00 KiB
local     8.00 KiB

Before the first insert, check the database name in the prompt, such as flights>. A misspelled name in use creates a second database at that insert, without a warning. PostgreSQL and SQL Server work the other way: CREATE DATABASE creates an empty database at once.

Create a MongoDB database in Atlas, Compass or Docker

Atlas runs the server for you, and Docker runs it in a container. Compass is MongoDB's desktop GUI for any server, Atlas included. Atlas and Compass ask for the database name and the first collection's name in the same dialog.

Create a database in MongoDB Atlas

In MongoDB Atlas, the hosted service, the steps are these[2]:

  1. In the sidebar, click Data Explorer under the Database heading.
  2. Open the Create Database dialog.
  3. Enter the Database Name and the Collection Name.
  4. Click Create Database.

Create a database in MongoDB Compass

Compass needs both names as well[6]:

  1. In the Connections Sidebar, click the icon to the right of your connection's name.
  2. Enter the database name and the first collection's name.
  3. Click Create Database.

Create a database with Docker

The official mongo image runs the server without installing it, and mongosh inside the container works as a local install does:

docker run -d --name mongodb-dev -p 27017:27017 -v mongodb-data:/data/db mongo:8
docker exec -it mongodb-dev mongosh

The -v option keeps the data files in a Docker volume, mongodb-data. A new container started with the same -v option still lists flights in show dbs. Without -v, each new container starts empty.

Create a MongoDB database visually in DbSchema

DbSchema connects to MongoDB and draws each collection on a diagram. The steps follow DbSchema's MongoDB documentation:

  1. Choose File → New Model, click MongoDb, and press Connect.
  2. In the Connect to MongoDB dialog, press Create New beside Database, type flights2, and then press Connect.
The DbSchema Connect to MongoDB dialog, with the Create New button beside the Database field

Create the first collection in DbSchema

MongoDB stores flights2 only once it holds a collection. Create that collection from the diagram:

  1. Choose Model → Create Collection, and name it flightData.
  2. Add departureAirport, arrivalAirport and distance on the Fields tab.
  3. Leave Inferred ( no validation ) unticked, and confirm the dialog. Ticked, that box keeps the collection in the DbSchema model only.
The DbSchema Edit Collection dialog of a collection orders, with the Inferred ( no validation ) box at the top and the fields on the Fields tab

While DbSchema is connected, confirming the dialog creates flightData in MongoDB, and flights2 with it. The collection gets a validator: a $jsonSchema rule[4] that every document has to meet before MongoDB saves it. DbSchema keeps the same rule in its model.

For a collection without a validator, DbSchema reads the first 100 and the last 100 documents. It lists the fields, BSON types, nested documents and arrays it finds, an approximation that MongoDB does not enforce. Drag one field onto another to draw a virtual relation, which DbSchema keeps in its model only. The Data Explorer follows those relations from a document to the matching documents of the next collection. The HTML5 documentation exports the diagram as a vector image, with comments as mouse-over tooltips.

The CRUD operations lesson goes on from the database you created here. Download DbSchema at https://dbschema.com/download.html, connect it to your MongoDB server, and create the next collection on the diagram. Connecting, the diagram and creating collections work in the free Community Edition. Following relations in the Data Explorer needs DbSchema Pro, and so does documenting more than 12 collections. A new installation starts with a 15-day trial that has every feature.

Sources

  1. mongosh - the MongoDB Shell
  2. MongoDB Manual - Databases and Collections
  3. MongoDB Manual - Install MongoDB Community Edition
  4. MongoDB Manual - Schema Validation
  5. MongoDB Manual - Naming Restrictions
  6. MongoDB Compass - Create a Database

Create MongoDB databases and collections visually

DbSchema connects to MongoDB, samples your documents to draw each collection as a diagram, and lets you create databases, collections and fields without the shell. Connecting, reverse-engineering and interactive diagrams are in the free Community Edition.