0
0
MongoDBquery~5 mins

Rows vs documents thinking in MongoDB

Choose your learning style9 modes available
Introduction

Understanding the difference between rows and documents helps you organize data the right way. It makes working with databases easier and faster.

When deciding how to store customer information in a database.
When choosing between a table in SQL or a collection in MongoDB.
When designing a database for an app that needs flexible data.
When you want to know how to retrieve data efficiently.
When you need to update or add data without breaking existing structure.
Syntax
MongoDB
SQL row example:
(id, name, age)
(1, 'Alice', 30)

MongoDB document example:
{
  _id: ObjectId(...),
  name: 'Alice',
  age: 30
}
Rows are used in SQL databases and look like simple tables with columns and rows.
Documents are used in MongoDB and store data as flexible JSON-like objects.
Examples
This gets the row where the user's id is 1.
MongoDB
SQL row:
SELECT * FROM users WHERE id = 1;
This finds one document by its unique ID.
MongoDB
MongoDB document:
db.users.findOne({ _id: ObjectId('507f1f77bcf86cd799439011') });
Adds a new row to the users table.
MongoDB
SQL row insert:
INSERT INTO users (id, name, age) VALUES (2, 'Bob', 25);
Adds a new document to the users collection.
MongoDB
MongoDB document insert:
db.users.insertOne({ name: 'Bob', age: 25 });
Sample Program

This example shows how to add a document with flexible fields and then find it by name.

MongoDB
use testdb;

// Insert a document in MongoDB
 db.users.insertOne({ name: 'Alice', age: 30, hobbies: ['reading', 'hiking'] });

// Find the document
 db.users.find({ name: 'Alice' }).pretty();
OutputSuccess
Important Notes

Rows have fixed columns; documents can have different fields in each record.

Documents store related data together, which can reduce the need for joins.

Think of rows like spreadsheet rows, and documents like folders with files inside.

Summary

Rows are simple and fixed; documents are flexible and nested.

Use rows for structured, uniform data; use documents for varied, complex data.

Understanding this helps you pick the right database and design your data well.