Skip to content

MongoDB - Create Database

In MongoDB, creating a database is an implicit and straightforward operation. You don’t need a separate CREATE DATABASE command like in SQL.

The use <DATABASE_NAME> command in the MongoDB Shell (mongosh) is used to switch the current database context. If the specified database does not exist, MongoDB reserves the name. The database itself is only physically created on the server when you first store data in it.

use DATABASE_NAME

Let’s create and verify a new database called e-commerce.

  1. Switch to the new database. This command itself returns no output, but mongosh confirms the switch.
> use e-commerce
switched to db e-commerce
  1. Check the currently selected database using the db command.
> db
e-commerce
  1. Now, let’s list all databases on the server with show dbs. Notice that e-commerce is not yet on the list. This is because it contains no data.
> show dbs
admin ...MB
config ...MB
local ...MB
  1. To physically create the database, we need to insert at least one document. We’ll use the modern insertOne() method.
> db.products.insertOne({
name: "Wireless Mouse",
brand: "Logitech",
price: 49.99,
in_stock: true
})
{
acknowledged: true,
insertedId: ObjectId("638e3a2b1f8e1b3d6f12a3b4")
}

This single operation created both the e-commerce database and the products collection within it.

  1. Now, if we list the databases again, e-commerce will appear.
> show dbs
admin ...MB
config ...MB
e-commerce ...MB
local ...MB
  • Default Database: If you connect to MongoDB and don’t specify a database, your context will default to a database named test. Any collections created without switching will be stored there.
  • In Application Code: In a programming language like Node.js or Python, you don’t typically use a database. Instead, you get a database object from your client connection, like const db = client.db('e-commerce');, which achieves the same result of setting the context for subsequent operations.