What is Collection in MongoDB: Definition and Usage
collection is a group of documents, similar to a table in relational databases. It stores multiple JSON-like objects called documents, which can have different structures but belong to the same collection.How It Works
Think of a collection in MongoDB like a folder in your computer where you keep related files. Each file inside the folder is a document, which holds data in a flexible format called BSON (similar to JSON). Unlike traditional tables, collections do not require all documents to have the same structure, so you can store different types of data together.
This flexibility makes collections very useful for handling data that changes over time or has varying fields. When you add a document to a collection, MongoDB automatically manages it without needing a fixed schema, making it easy to scale and adapt your data storage.
Example
This example shows how to create a collection and insert documents into it using MongoDB shell commands.
use myDatabase // Insert documents into a collection named 'users' db.users.insertMany([ { name: "Alice", age: 25, city: "New York" }, { name: "Bob", age: 30, hobbies: ["reading", "hiking"] } ]) // Find all documents in the 'users' collection db.users.find()
When to Use
Use collections in MongoDB whenever you need to store groups of related data without strict structure requirements. They are ideal for applications where data formats can vary, such as user profiles, product catalogs, or event logs.
Collections work well when you want to quickly add or change fields without redesigning the database schema. They also support high scalability and flexible querying, making them suitable for modern web and mobile apps.
Key Points
- A collection is a container for documents in MongoDB, similar to a table in SQL.
- Documents in a collection can have different fields and structures.
- Collections do not enforce a fixed schema, allowing flexible data storage.
- They support fast queries and easy scaling for large datasets.