Database, Collection, and Document in MongoDB
This tutorial introduces you to the core elements of MongoDB—databases, collections, and documents. These fundamental building blocks of MongoDB enable developers to structure and interact with data efficiently. Whether you are new to databases or transitioning from SQL, this guide provides a strong foundation.
What is a Database?
A database in MongoDB is a container for collections. It acts as a project-level bucket where all related data resides. Unlike SQL databases, MongoDB databases are created automatically when referenced for the first time. Simply type use <database_name>
in the Mongo shell, and MongoDB will create and switch to that database if it doesn’t exist.
Collections: Equivalent to Tables
A collection is analogous to a table in SQL but is more flexible. It groups related data items together. Collections are also created implicitly when you insert data into them. For example:
db.myCollection.insert({ name: "Example Item" });
This command creates the myCollection
and inserts a new document.
Documents: JSON-Like Objects
A document is the fundamental data unit in MongoDB, stored as a JSON-like object. Each document is a record with a unique _id
field, ensuring easy indexing and access. Example of a document:
{
"_id": "unique-id",
"name": "Alice",
"skills": ["JS", "Python", "MongoDB"]
}
Documents can store arrays, nested objects, and other rich data types.
Practical Tips
- Switch Between Databases: Use
db
to see the current database. Switch databases usinguse <database_name>
. - Insert Data: Use
insert()
to add a document to a collection. MongoDB automatically assigns a unique_id
. - Query Data: Use
find()
to retrieve documents. Chain.pretty()
for formatted output.
Example:
db.myCollection.find().pretty();
Summary
MongoDB’s structure simplifies data handling through its JSON-based documents and dynamic schema. With just a few commands, you can create databases, organize collections, and manage rich data documents.
Ready to dive deeper? The next tutorial covers preparing data for MongoDB!
Ready to Level Up Your Skills?
Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!
Enroll Now for Free!