AI Computer Institute
Expert-curated CS & AI curriculum aligned to CBSE standards. A bharath.ai initiative. About Us

MongoDB Basics: NoSQL Document Databases

📚 Technology⏱️ 19 min read🎓 Grade 8
✍️ AI Computer Institute Editorial Team Updated: August 2026 CBSE-aligned · Peer-reviewed · 19 min read
Content curated by subject matter experts with IIT/NIT backgrounds. All chapters are fact-checked against official CBSE/NCERT syllabi.

Imagine your school office keeps one big register for every student in Grade 8. Most rows look the same: name, roll number, section, marks. But then you reach Ananya's row. Ananya is on the state badminton team, so the register also needs to track her coach's name and her tournament record. A few rows later there's Priya, who runs the school's Robotics Club and needs a "club role" column instead. If every student's row has to fit the exact same set of columns, the register office has two bad choices: leave dozens of cells blank for students who don't play a sport or run a club, or keep creating new, mostly-empty columns every time one student needs one new fact recorded about them. Neither feels right. This chapter is about a different way of storing records — one where each entry carries exactly the information it needs, no more and no less. That idea is the heart of MongoDB, the most widely used NoSQL document database.

Why Rows and Columns Start to Creak

The register-book idea is exactly how a traditional relational database table works — the kind you may have already met as rows and columns, similar to a spreadsheet. A table forces every single record (every row) to have the same fixed set of columns. That rule is powerful when your data really is uniform — every bank account has a balance, every railway ticket has a PNR number. But it becomes a burden the moment different records naturally need different extra facts.

Let's make this concrete with actual numbers. Suppose the Grade 8 table has three students and five columns: Name, Grade, Sport, Coach, Scholarship. Only Ananya plays a sport, so only her row uses the last three columns.

Name    Grade  Sport       Coach       Scholarship
Ananya  8      Badminton   R. Verma    Yes
Kabir   8      —           —           —
Priya   8      —           —           —

Count the cells in those three "extra" columns: 3 students × 3 columns = 9 cells total. Only 3 of them (Ananya's row) actually hold information. The other 6 are empty. That's 6 ÷ 9 = 0.666..., or about 67% wasted space in just this small slice of the table — and in a real school database with hundreds of students and dozens of possible special fields (sport, music grade, medical note, transport route, scholarship type), the wasted, mostly-empty columns pile up fast. Worse, the moment Priya's robotics role needs recording, someone has to redesign the whole table and add yet another column that helps only her.

This rigidity is the exact problem NoSQL document databases were built to solve.

A Document: A Record That Carries Its Own Shape

MongoDB stores each record as a document — a set of field-and-value pairs written in a format that looks almost exactly like JSON (JavaScript Object Notation), a text format for representing structured data that you may have already seen in web apps. Here is Ananya as a MongoDB document:

{
  name: "Ananya Sharma",
  grade: 8,
  section: "B",
  rollNumber: 14,
  subjects: ["Maths", "Science", "AI", "Hindi"],
  sport: "Badminton",
  coach: "R. Verma",
  scholarship: true
}

And here is Kabir, stored in the very same collection, right next to Ananya:

{
  name: "Kabir Mehta",
  grade: 8,
  section: "B",
  rollNumber: 15,
  subjects: ["Maths", "Science", "AI", "Sanskrit"]
}

Notice what just happened: Kabir's document has no sport, coach, or scholarship fields at all — not empty ones, absent ones. Nobody had to redesign anything to fit Kabir in. When Priya joins the collection with a completely different extra fact — her robotics club role — her document simply includes the fields relevant to her:

{
  name: "Priya Nair",
  grade: 8,
  section: "A",
  rollNumber: 3,
  subjects: ["Maths", "Science", "AI", "French"],
  clubName: "Robotics Club",
  clubRole: "Captain"
}

Three students, three different sets of fields, zero wasted blank cells, and no need to redesign a shared table every time one student's record needs one more fact. That flexibility — each record defining its own shape — is what "schema-flexible" means, and it is the single biggest reason document databases exist.

The Diagram: Table Versus Document Collection

Relational Table (fixed columns) MongoDB Collection (flexible documents) Name Grade Sport Coach Scholar? Ananya 8 Badminton R. Verma Yes Kabir 8 empty empty empty Priya 8 empty empty empty 6 of 9 "extra" cells wasted (Priya's club role has nowhere to go) { Document 1 name: "Ananya Sharma", sport: "Badminton", coach: "R. Verma", scholarship: true } { Document 2 name: "Kabir Mehta", subjects: [4 items] } ← no sport/coach fields at all { Document 3 name: "Priya Nair", clubName: "Robotics Club", clubRole: "Captain" } Every field present is real data — nothing wasted, nothing forced

The Vocabulary Shift: Tables Become Collections

MongoDB's terms map onto ideas you already understand from tables, but each one is a little looser:

  • A collection plays the role a table used to play — it's a named bucket that holds related documents, like students. But unlike a table, it does not force every document inside it to share the same columns.
  • A document plays the role a row used to play — it's one record. But unlike a row, it can have its own private set of fields.
  • A field plays the role a column used to play — a named piece of data inside a document, like rollNumber. But fields aren't declared in advance for the whole collection; each document simply lists whichever fields it needs.
  • Every document gets an _id field automatically if you don't supply one — MongoDB generates a unique 12-byte value called an ObjectId for it. This plays the same role a primary key plays in a table: no two documents in a collection ever share an _id, so it's always a reliable way to find one exact document again.

This is why MongoDB calls itself a document database, and why it's grouped under the broader label NoSQL ("not only SQL") — a family of databases that don't use the rigid table-and-fixed-column model that SQL-based relational databases (like MySQL or PostgreSQL) are built around. MongoDB itself was first released in 2009 by a company that later renamed itself MongoDB Inc., and it quickly became the most widely used document database because its JSON-like documents map naturally onto the objects programmers already build in languages like JavaScript and Python.

Nesting: Nobody Said a Field Has to Be Simple

A relational table cell can usually only hold one small piece of data — a number, a short string. A MongoDB field can hold something much richer: a whole list, or even another mini-document, nested right inside. Look at how naturally an address fits inside a student document, instead of needing a separate "addresses" table joined back by an ID:

{
  name: "Ananya Sharma",
  grade: 8,
  address: {
    city: "Pune",
    state: "Maharashtra",
    pincode: "411001"
  },
  marks: {
    Maths: 92,
    Science: 88,
    AI: 95,
    Hindi: 79
  }
}

address here is a nested document — a field whose value is itself a set of field-value pairs. This is called embedding. It matches how we already think about the data: "Ananya's address" is naturally part of "Ananya," not a separate thing you have to go looking for elsewhere.

The marks field lets us do a genuinely useful calculation. To find Ananya's average, we simply add all four values and divide by how many subjects there are — the same arithmetic you'd do by hand:

average = (92 + 88 + 95 + 79) / 4
        = 354 / 4
        = 88.5

A program reading this document doesn't need to run a query joining four separate tables to get these four numbers — they're already sitting together inside one document, exactly where you'd expect to find them.

Talking to MongoDB: Reading and Writing Documents

MongoDB is controlled using a shell called mongosh (Mongo Shell), where commands read almost like plain JavaScript function calls on a collection. Let's insert both students from earlier into a collection named students:

db.students.insertOne({
  name: "Ananya Sharma",
  grade: 8,
  section: "B",
  rollNumber: 14,
  subjects: ["Maths", "Science", "AI", "Hindi"],
  sport: "Badminton",
  coach: "R. Verma",
  scholarship: true
})

db.students.insertOne({
  name: "Kabir Mehta",
  grade: 8,
  section: "B",
  rollNumber: 15,
  subjects: ["Maths", "Science", "AI", "Sanskrit"]
})

To read documents back, we use find() with a filter — a small document describing what we're looking for. To get every scholarship student in Grade 8:

db.students.find({ grade: 8, scholarship: true })

Let's trace this carefully, because it teaches something important. MongoDB checks each document in students against both conditions. Ananya's document has grade: 8 and scholarship: true — it matches, and comes back in the result. Kabir's document has grade: 8, but it has no scholarship field at all — a missing field never equals true, so his document is correctly left out. The query returns exactly one document: Ananya's.

Updating one field doesn't require rewriting the whole document. Suppose Kabir's roll number changes:

db.students.updateOne(
  { name: "Kabir Mehta" },
  { $set: { rollNumber: 16 } }
)

The first document is the filter (which document to touch), and $set is an update operator that changes just the named field, leaving every other field in Kabir's document untouched. Deleting a document is just as direct:

db.students.deleteOne({ name: "Kabir Mehta" })

Together, insertOne, find, updateOne, and deleteOne are the four basic operations every database needs — commonly remembered by the acronym CRUD: Create, Read, Update, Delete.

Filtering With Comparison Operators

Real questions are rarely just "equals." MongoDB provides comparison operators, written as fields starting with $, for questions like "roll number greater than 10":

db.students.find({ rollNumber: { $gt: 10 } })

Here $gt means "greater than" — the filter reads as "find documents where rollNumber is greater than 10." To check whether an array field contains a particular value — for instance, every student who studies AI — MongoDB lets you match directly against the array:

db.students.find({ subjects: "AI" })

This works because when the field being tested is an array, MongoDB automatically checks whether any element of that array equals the value given — no special syntax needed for the simple case. For matching against several possible values at once, the $in operator is more direct: db.students.find({ grade: { $in: [7, 8] } }) finds every student in Grade 7 or Grade 8.

Correcting a Common Misconception

A mistake many beginners make is thinking "NoSQL" means "no rules, no structure, just throw in anything." That's wrong in two ways. First, in a well-designed collection, documents are still expected to follow a common shape most of the time — every student document should have a name and grade — it's just that MongoDB doesn't force this at the database level the way a table does. The discipline of keeping documents consistent becomes the application's responsibility (or can even be enforced by MongoDB itself using a feature called schema validation, which rejects documents that don't match rules you define). "Schema-flexible" means the shape can adapt when it genuinely needs to — like Priya's robotics fields — not that the shape is meaningless.

Second, some beginners assume document databases can't represent relationships between different pieces of data at all, since there's no built-in "join" like in SQL. That's also not quite right. MongoDB supports two strategies: embedding related data directly inside a document (as we did with address and marks), or referencing — storing another document's _id as a field, similar to how a foreign key works in a relational table, and looking that document up separately when needed. The choice between embedding and referencing is a real design decision: embed data that's almost always read together and rarely changes independently (an address inside a student record); reference data that's large, shared across many documents, or changes on its own schedule (a school's list of subjects, referenced by ID from many student documents rather than copied into each one).

Choosing Between a Table and a Document

Document databases aren't a universal upgrade over relational ones — they're a different tradeoff, better suited to certain kinds of data. Think about an online marketplace catalog, similar to what a site like Flipkart manages: a phone listing needs fields like RAM and storage capacity, while a kurta listing needs fields like fabric and size — two products in the very same catalog, with almost no overlapping attributes. Forcing both into one rigid table would recreate exactly the mostly-empty-column problem from the start of this chapter; a MongoDB collection lets each product document carry only the attributes that product actually has.

On the other hand, consider a bank transferring money between two accounts, or a railway system confirming a seat only if it hasn't already been given to someone else. These operations need very strict, all-or-nothing guarantees across multiple related tables at once — exactly what relational databases were built to guarantee first. That doesn't mean MongoDB can't do it (modern MongoDB does support these guarantees), but the relational model's fixed structure and mature tools for enforcing strict cross-table consistency are often still the more natural fit there. Good database design starts by asking what your data actually looks like — uniform and tightly interconnected, or varied and naturally self-contained — before picking a tool.

One more practical strength worth naming: because a huge collection of documents can be split up and spread across many different computers — a technique called sharding — MongoDB scales well for applications with enormous, fast-growing amounts of data, which is one reason it's a common choice behind large web and mobile applications. That's a deeper topic for a later chapter, but it's worth knowing the word.

Summary

  • A relational table forces every record to share the exact same fixed columns, which wastes space and forces redesigns when different records naturally need different extra facts.
  • MongoDB stores each record as a document — a JSON-like set of field-value pairs — grouped into a collection. Different documents in the same collection can have different fields.
  • Every document has a unique _id (an ObjectId if not supplied manually), playing the role a primary key plays in a table.
  • Fields can hold simple values, arrays, or nested documents (embedding) — letting closely related data live together in one document instead of being split across separate tables.
  • The four CRUD operations — insertOne, find, updateOne, deleteOne — create, read, update, and delete documents; query filters can use comparison operators like $gt and $in.
  • "Schema-flexible" is not "no structure" — documents are still designed with a common shape in mind, and MongoDB can enforce validation rules; relationships between documents can be modeled by embedding or by referencing an _id, similar to a foreign key.
  • Document databases suit varied, self-contained data (product catalogs, user profiles); relational databases still often suit tightly interconnected data needing strict, all-or-nothing guarantees (banking transfers, seat booking).

Test Yourself

  • Ananya's document has a coach field; Kabir's document has no coach field at all. If you run db.students.find({ coach: { $exists: false } }), which of the two documents would you expect back, and why? (Think about what "field doesn't exist" means for each of them.)
  • A school wants to store, for every student, the name and phone number of up to three emergency contacts. Would you model "emergency contacts" as a nested array of small documents inside each student document, or as a completely separate collection referenced by _id? Justify your choice using the embedding-versus-referencing idea from this chapter.
  • A collection of 40 students has a sparse table equivalent with 6 optional columns. Only 5 of the 40 students fill in all 6 of those columns; the other 35 students leave all 6 blank. Using the same arithmetic method from earlier in the chapter, calculate what percentage of the 40 × 6 = 240 optional cells sit empty in the table version.
  • Explain in your own words why "NoSQL" is a misleading name if someone assumes it means "the data has no structure at all."

Practice Exercises

Now it is time to practice! Complete these challenges to solidify your understanding:

  • Exercise 1: Write a short program that demonstrates the core concept from this chapter. Test it with at least 3 different inputs.
  • Exercise 2: Find a real-world example where mongodb basics: nosql document databases is used in an Indian company (like TCS, Infosys, Flipkart, or ISRO). Write a paragraph explaining the connection.
  • Exercise 3: Create a mind-map connecting mongodb basics: nosql document databases to at least 3 other topics you have studied.
← SQLite with Python: Your Portable DatabaseTime Complexity →

Found this useful? Share it!

📱 WhatsApp 🐦 Twitter 💼 LinkedIn