Collections and tables both store data, but in different database types. Understanding their difference helps you work with data easily.
0
0
Collections vs tables mental model in MongoDB
Introduction
When you want to store data in a flexible way without fixed columns.
When you need to organize data in a traditional, structured format with rows and columns.
When switching between SQL and MongoDB databases and want to understand how data is stored.
When designing a new database and deciding how to group your data.
When explaining database concepts to someone new to databases.
Syntax
MongoDB
No direct code syntax since this is a concept comparison.A table is used in SQL databases and has rows and columns.
A collection is used in MongoDB and stores documents without fixed columns.
Examples
This creates a table named
users with fixed columns.MongoDB
SQL Table example:
CREATE TABLE users (
id INT PRIMARY KEY,
name VARCHAR(100),
age INT
);This adds a document to the
users collection without fixed columns.MongoDB
MongoDB Collection example:
db.users.insertOne({ name: "Alice", age: 30 });Sample Program
This example shows how a MongoDB collection can store documents with different fields, unlike a SQL table.
MongoDB
use testdb // Insert documents into MongoDB collection db.users.insertMany([ { name: "Alice", age: 30 }, { name: "Bob", city: "New York" } ]); // Query all documents db.users.find().pretty();
OutputSuccess
Important Notes
Collections do not require a fixed structure, so documents can have different fields.
Tables require a fixed schema, so every row has the same columns.
MongoDB collections are more flexible for changing data needs.
Summary
Tables store data in rows and columns with a fixed schema.
Collections store flexible documents without fixed columns.
Understanding this helps when moving between SQL and MongoDB.