0
0
MongoDBquery~5 mins

Tables vs collections thinking in MongoDB

Choose your learning style9 modes available
Introduction

We use tables or collections to organize data. Understanding the difference helps us choose the right way to store and find information easily.

When deciding how to store customer information in a database.
When planning how to save product details for an online store.
When figuring out how to organize blog posts and comments.
When switching from a traditional database to MongoDB.
When explaining data storage to someone new to databases.
Syntax
MongoDB
Table: A structured set of rows and columns.
Collection: A group of documents stored together in MongoDB.

Tables are used in SQL databases and have fixed columns.

Collections are used in MongoDB and store flexible documents.

Examples
This creates a table with fixed columns for id, name, and email.
MongoDB
SQL Table example:
CREATE TABLE users (
  id INT PRIMARY KEY,
  name VARCHAR(100),
  email VARCHAR(100)
);
This adds a document to the users collection with flexible fields.
MongoDB
MongoDB Collection example:
db.users.insertOne({
  name: "Alice",
  email: "alice@example.com",
  age: 30
});
Sample Program

This example shows how to add items to a MongoDB collection and then list them.

MongoDB
use mydatabase

// Insert documents into a collection
 db.products.insertMany([
   { name: "Pen", price: 1.5, color: "blue" },
   { name: "Notebook", price: 3.0, pages: 100 }
 ]);

// Find all products
 db.products.find().pretty();
OutputSuccess
Important Notes

Tables require a fixed structure; collections allow flexible fields per document.

Collections can store different shapes of data in the same group.

Think of tables like spreadsheets and collections like folders with different papers inside.

Summary

Tables are for structured, fixed data in rows and columns.

Collections hold flexible documents without fixed columns.

Choosing between them depends on how you want to organize and use your data.