keepcalculator

06 Numbers and Powers

Create Database MongoDB: Setup & First Steps

Card No. 06·66165 · Updated · Standard formula, shown below

To create a database in MongoDB, you use the use command in the MongoDB shell (e.g., use myNewDatabase), which switches to that database and creates it implicitly when you first insert a document. You don’t need a separate “CREATE DATABASE” statement like in SQL; MongoDB creates the database and collection on the fly when you write data. This article explains the exact steps, the underlying behavior, and common pitfalls.

What “Creating a Database” Actually Means in MongoDB

Unlike relational databases where you run CREATE DATABASE and the database exists immediately (even if empty), MongoDB uses a lazy creation model. The database is only physically created when you insert the first document into a collection. If you run use mydb and then immediately run show dbs, you won’t see mydb in the list because it doesn’t exist yet. This behavior often confuses newcomers. The database appears only after you add data.

For example, in the MongoDB shell:

  1. Type use myNewDatabase – the shell responds with switched to db myNewDatabase.
  2. Type db.myCollection.insertOne({name: "Alice"}) – this creates both the database and the collection.
  3. Type show dbs – now myNewDatabase appears in the list.

This lazy creation also applies to collections. A collection is created when you insert a document into it, unless you explicitly use db.createCollection() (which is only needed for capped collections or to pre-define validation rules).

Step-by-Step: Create a Database via the Shell

Here’s the exact sequence for the most common way—using the mongosh shell (the modern replacement for the old mongo shell):

  • Start the MongoDB service (e.g., mongod on Linux/macOS, or the Windows service).
  • Open a terminal and run mongosh to connect to the default local instance (port 27017).
  • Type use myDatabase and press Enter.
  • Insert a document: db.users.insertOne({username: "jdoe", email: "j@example.com"}).
  • Verify: show dbs – you’ll see myDatabase listed.

If you’re using MongoDB Atlas (the cloud service), you don’t use the shell. Instead, in the Atlas UI, you click “Browse Collections” and then “Create Database”. You enter a database name and a collection name. The database is created immediately, but it still won’t show up in the cluster’s database list until you add a document.

How to Choose a Database Name

MongoDB has naming restrictions you must follow to avoid errors:

  • Database names cannot contain /, \, ., ", $, or the null character.
  • They cannot be empty and must be less than 64 bytes (UTF-8).
  • On Windows, you cannot use certain reserved names like con, prn, aux, nul, com1–com9, lpt1–lpt9.
  • Case sensitivity matters: MyDB and mydb are different databases.

For collection names, the rules are simpler: they can contain almost any character, but cannot contain the null character, cannot start with system. (reserved), and cannot exceed 255 characters. It’s good practice to use lowercase names with underscores or camelCase.

Common Problems and Misconceptions

Here are the most frequent issues people hit when creating a database:

  • Database doesn’t appear in show dbs: This is normal if you haven’t inserted data yet. Insert a document and it will appear.
  • Permission errors: If you’re using authentication, your user must have the dbAdmin or readWrite role on that database. Otherwise you’ll get an “unauthorized” error.
  • Connecting to the wrong server: If you run mongosh on a machine that doesn’t have MongoDB running, you’ll get a connection refused error. Make sure mongod is running first.
  • Using db.createCollection() unnecessarily: You don’t need it for normal collections; it only matters for capped collections (fixed-size) or to set validation rules at creation time.
  • Mixing up database and collection: A database holds collections, and a collection holds documents. You create the database implicitly, but you must specify a collection when inserting data.

A common misconception is that MongoDB requires a schema. It doesn’t—documents in the same collection can have different fields. However, you can enforce a schema using validation rules if you want.

Creating a Database Programmatically (Node.js, Python, etc.)

In application code, you don’t use the use command. Instead, you connect to the MongoDB server and specify the database name in the connection string or in the client object. The database is created when you first write to it.

For example, in Node.js with the official driver:

  1. Install the driver: npm install mongodb.
  2. Connect: const { MongoClient } = require('mongodb'); const client = new MongoClient('mongodb://localhost:27017');
  3. Get the database: const db = client.db('myAppDB'); – this does NOT create it yet.
  4. Insert a document: await db.collection('users').insertOne({name: 'Bob'}); – now the database and collection exist.

In Python (PyMongo):

  1. Install: pip install pymongo.
  2. Connect: from pymongo import MongoClient; client = MongoClient('mongodb://localhost:27017').
  3. Get database: db = client['myAppDB'].
  4. Insert: db.users.insert_one({'name': 'Bob'}).

In both cases, the database is created lazily on the first insert. If you want to create it without inserting data, you can call db.createCollection('myCollection') explicitly, which forces the database to exist.

When to Use MongoDB vs. SQL

MongoDB is a document database, ideal for applications with flexible, evolving schemas, such as content management systems, real-time analytics, and IoT data. It stores data as BSON (binary JSON) documents, which map naturally to objects in most programming languages. SQL databases (PostgreSQL, MySQL) are better for highly relational data, complex joins, and transactions that require ACID guarantees across multiple tables.

MongoDB does support multi-document transactions (since version 4.0), but they are more limited than in SQL and come with performance costs. If your data is naturally hierarchical (e.g., a user with multiple addresses), MongoDB’s embedded documents are simpler than SQL’s multiple tables with foreign keys.

Frequently Asked Questions

How do I delete a MongoDB database?

Use db.dropDatabase() from within the database you want to delete (after switching to it with use). This permanently removes the database and all its collections. There is no undo, so make sure you have a backup. In Atlas, you can delete a database from the UI, but you must first delete all collections.

Can I create a database without inserting data?

Technically yes, by using db.createCollection() after use. This forces the database to exist. However, the database will still not appear in show dbs until it has at least one collection with data or a non-empty collection. In practice, it’s simpler to just insert a document.

What is the difference between a database and a collection in MongoDB?

A database is a container for collections, similar to a schema in SQL. A collection is a group of documents, analogous to a table. In SQL, a table has rows with fixed columns; in MongoDB, a collection has documents with flexible fields. You can have many collections in one database.

Why does MongoDB create databases automatically?

This design reduces friction for developers. You don’t have to run a separate creation command; just start writing data. It also makes it easy to create a new database per test or per tenant without administrative overhead. The downside is that a typo in a database name can silently create a new database, so always double-check your connection string.

Can I use MongoDB without installing it locally?

Yes, MongoDB Atlas offers a free tier (M0) that runs in the cloud. You create a cluster, get a connection string, and connect from anywhere. This is the easiest way to try MongoDB without managing a local server. The free tier includes 512 MB of storage, which is enough for learning and small projects.

How do I check if a database exists before creating it?

You can list all databases with show dbs or in code with client.db().admin().listDatabases(). To check if a specific database exists, you can try to read from it, but because of lazy creation, an empty database won’t show up. If you need to know for sure, use listDatabases and check the names array.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →