Databases, Collections & Documents
How MongoDB organises data, and how to create your first database and collection.
What you will learn
- Create a database and collection
- Understand the _id field
- Know how data is structured
The hierarchy
A MongoDB server holds databases; each database holds collections; each collection holds documents. You do not create them in advance — MongoDB makes a database/collection automatically the first time you insert into it.
use myapp // switch to (and create) the "myapp" database
db.users.insertOne({ // creates the "users" collection on first insert
name: "Asha",
email: "asha@example.com"
})Two commands here. use myapp switches you to a database called myapp — and if it does not exist yet, MongoDB will make it the moment you put data in. db.users.insertOne({...}) then adds one document to a collection called users. You never had to “create” the users collection first; inserting into it brings it to life.
Note: Output:
{ acknowledged: true, insertedId: ObjectId('65f1a2b3c4d5e6f7a8b9c0d1') }
MongoDB confirms the insert and hands back the _id it generated for the new document. Your id value will be different — every one is unique.
The _id field
Every document automatically gets a unique _id (an ObjectId). You can also set your own. It uniquely identifies the document forever.
{
"_id": ObjectId("65f1a2b3c4d5e6f7a8b9c0d1"),
"name": "Asha",
"email": "asha@example.com"
}Notice the extra _id field at the top — you did not type it, MongoDB added it. An ObjectId is a special 24-character value that is guaranteed to be unique, so no two documents ever clash. Whenever you want to find, update or delete this exact document later, you point at its _id.
Tip: You rarely run raw shell commands in a MERN app — you will use Mongoose (covered soon) from your Node code. But understanding databases → collections → documents makes everything click.
Q. When is a MongoDB collection created?
✍️ Practice
- In Compass (or mongosh), create a database and insert one document.
- Find the
_idof the document you inserted.
🏠 Homework
- Plan the collections a blog app would need (e.g. users, posts, comments).