⬅ Previous Topic
MongoDB Data TypesNext Topic ⮕
Using MongoDB Compass⬅ Previous Topic
MongoDB Data TypesNext Topic ⮕
Using MongoDB CompassBefore 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.
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.
There are two ways to create a collection:
db.createCollection()
db.users.insertOne({
name: "Alice",
age: 25
});
Output:
{ acknowledged: true, insertedId: ObjectId("...") }
This command automatically creates the users
collection and inserts the document.
db.createCollection("products")
Output:
{ ok: 1 }
You can now insert documents into the products
collection.
db.products.insertOne({
name: "Laptop",
price: 75000,
inStock: true
});
Output:
{ acknowledged: true, insertedId: ObjectId("...") }
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.
show dbs
Output:
admin 0.000GB config 0.000GB local 0.000GB myFirstDB 0.000GB (only appears if a document was inserted)
show collections
Output:
products users
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.
use dbName
switches or creates a databasedb.collection.insertOne()
creates the collection (and database) implicitlydb.createCollection("name")
explicitly creates a collectionshow dbs
and show collections
help you view the structureIn the next lesson, we will learn how to insert multiple documents and understand how data is stored in MongoDB collections.
⬅ Previous Topic
MongoDB Data TypesNext Topic ⮕
Using MongoDB CompassYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.