MongoDB - Create Database
MongoDB - Create a Database
Section titled “MongoDB - Create a 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 Command
Section titled “The use Command”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.
Syntax
Section titled “Syntax”use DATABASE_NAMEExample Walkthrough
Section titled “Example Walkthrough”Let’s create and verify a new database called e-commerce.
- Switch to the new database. This command itself returns no output, but
mongoshconfirms the switch.
> use e-commerceswitched to db e-commerce- Check the currently selected database using the
dbcommand.
> dbe-commerce- Now, let’s list all databases on the server with
show dbs. Notice thate-commerceis not yet on the list. This is because it contains no data.
> show dbsadmin ...MBconfig ...MBlocal ...MB- 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.
- Now, if we list the databases again,
e-commercewill appear.
> show dbsadmin ...MBconfig ...MBe-commerce ...MBlocal ...MBImportant Notes
Section titled “Important Notes”- 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
usea database. Instead, you get a database object from your client connection, likeconst db = client.db('e-commerce');, which achieves the same result of setting the context for subsequent operations.