MongoDB - Getting StartedMongoDB - Getting Started1

Creating a Database and Collection in MongoDB



Creating a Database and Collection in MongoDB

Before you can store documents in MongoDB, you need a database and a collection. Think of a database as a folder, and a collection as a file inside that folder that holds your JSON-like documents.

Using the MongoDB Shell to Create a Database

To start the Mongo shell, run:

mongo

Now, to create or switch to a database:

use myFirstDB

Output:

switched to db myFirstDB

Note: The database is not created immediately. It only gets created when you add a collection and insert data into it.

Creating a Collection

There are two ways to create a collection:

Method 1: Implicit Creation (Most Common)


db.users.insertOne({
  name: "Alice",
  age: 25
});
    

Output:

{
  acknowledged: true,
  insertedId: ObjectId("...")
}
    

This command automatically creates the users collection and inserts the document.

Method 2: Explicit Creation

db.createCollection("products")

Output:

{ ok: 1 }
    

You can now insert documents into the products collection.

Inserting into the Explicitly Created Collection


db.products.insertOne({
  name: "Laptop",
  price: 75000,
  inStock: true
});
    

Output:

{
  acknowledged: true,
  insertedId: ObjectId("...")
}
    

Intuition Check

Q: Why doesn't MongoDB create the database immediately when you type use myFirstDB?

A: Because MongoDB uses lazy creation. A database is only created when data is actually inserted. This saves space and keeps the system efficient.

Listing All Databases

show dbs

Output:

admin     0.000GB
config    0.000GB
local     0.000GB
myFirstDB 0.000GB  (only appears if a document was inserted)
    

Listing All Collections in the Current Database

show collections

Output:

products
users
    

Intuition Check

Q: Can you insert data into a collection before creating the database?

A: Yes! MongoDB automatically creates the database and the collection for you as soon as you insert data.

Summary

In the next lesson, we will learn how to insert multiple documents and understand how data is stored in MongoDB collections.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

Mention your name, and programguru.org in the message. Your name shall be displayed in the sponsers list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M