How to create a database in MongoDB
MongoDB has no CREATE DATABASE. What actually creates one (and what doesn't), the exact errors for bad names, and examples for mongosh, Node and Python.
Quick Answer
There is no create command. Switch to the new name with use, then write something to it:
use shop
db.createCollection('orders') // the database now exists
Inserting a document works too: db.orders.insertOne({ item: 'pen' }) creates the database and the collection in one step.
Why use alone does not create anything
use shop only changes which database the shell sends commands to. Nothing is written to the server, so the database doesn't show up anywhere yet:
use shop // switched to db shop
show dbs // shop is not listed
db.createCollection('orders')
show dbs // shop 8.00 KiB
MongoDB creates a database the first time something is stored in it, and removes it when its last collection is dropped. That's why a database you "created" earlier can vanish if you never inserted anything.
Two ways to create it
| Command | What it creates | Use it when |
|---|---|---|
db.createCollection('orders') | The database and an empty collection | You want to set options first: a validator, capped size, collation or time series |
db.orders.insertOne({ ... }) | The database, the collection and a document | You have data ready to go |
use shop
// with options: a collection that rejects documents without an email
db.createCollection('customers', {
validator: { $jsonSchema: { required: ['email'] } }
})
For more on validators, see our guide to MongoDB JSON schema validation.
Create a database without switching to it
In a script you can stay where you are and get a handle to any database with db.getSiblingDB():
db.getSiblingDB('analytics').createCollection('events')
From a terminal, put the database name in the connection string and pass the command with --eval:
mongosh "mongodb://localhost:27017/shop" --eval "db.createCollection('orders')"
From Node.js
client.db('shop') returns a handle without touching the server. The database appears when you write:
import { MongoClient } from 'mongodb'
const client = new MongoClient(process.env.MONGODB_URI)
await client.connect()
const db = client.db('shop') // nothing created yet
await db.createCollection('orders') // now shop exists
await client.close()
From Python (PyMongo)
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017")
db = client["shop"] # lazy, nothing created yet
db["orders"].insert_one({"item": "pen"})
print("shop" in client.list_database_names()) # True
What we found testing this
1. Reads never create a database, but createIndex() does
We ran each of these against database names that didn't exist, then checked show dbs:
| Operation on a missing database | Creates it? |
|---|---|
use newdb | No |
db.x.find() | No |
db.x.countDocuments() | No |
db.createUser(...) | No. The user is stored in admin.system.users |
db.x.createIndex({ a: 1 }) | Yes, with collection x |
db.x.insertOne({}) | Yes |
So an app that runs createIndexes on startup will create its database even before any data arrives.
2. The exact errors for bad names
Some names are rejected by mongosh before they reach the server, and others by the server:
use my.db
// MongoshInvalidInputError: [COMMON-10001] Invalid database name: my.db
db.getSiblingDB('price$').t.insertOne({})
// MongoServerError: Invalid namespace: price$.t
db.getSiblingDB('a'.repeat(64)).t.insertOne({})
// MongoServerError: db name must be at most 63 characters, found: 64
// with "Shop" already on the server:
db.getSiblingDB('shop').t.insertOne({})
// MongoServerError: db already exists with different case already have: [Shop] trying to create [shop]
3. Calling createCollection() twice: drivers disagree
The server accepts a repeat createCollection with the same options and returns { ok: 1 }. mongosh and the Node.js driver pass that through, so the call is safe to repeat. PyMongo checks first and raises CollectionInvalid: collection orders already exists. With different options (say, adding capped: true), every client gets NamespaceExists.
Naming rules
- Names can't contain
/,\,.,",$, spaces or a null character, and can be at most 63 characters long. - Names are case-sensitive, but two databases that differ only by case can't coexist (error code 13297, shown above).
- Don't use
admin,configorlocal. Those are system databases.
A typo in use silently gives you a new, empty database instead of an error. If a query returns nothing, run db and show dbs to check you're where you think you are.
Frequently Asked Questions
Is there a CREATE DATABASE command in MongoDB?
No. A database is created automatically the first time you create a collection or insert a document in it.
Why does my new database not show in show dbs?
It has no collections yet. use only switches context. Create a collection or insert a document and it will appear.
How do I create a user for the new database?
Switch to it with use and run db.createUser() with a role such as readWrite on that database. See the create user guide for the full syntax.
How do I create a database in MongoDB Atlas?
In the Atlas UI, open Browse Collections and choose Create Database, which asks for a first collection name. From mongosh connected to Atlas, the same use and createCollection steps work.