MongoDB BasicsCore· 30 min read

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.

mongosh: create a db and collection by inserting
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.

The auto-generated _id
{
  "_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?

Answer: MongoDB creates the database and collection automatically the first time you insert a document into them.

✍️ Practice

  1. In Compass (or mongosh), create a database and insert one document.
  2. Find the _id of the document you inserted.

🏠 Homework

  1. Plan the collections a blog app would need (e.g. users, posts, comments).
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →