What is a Collection in MongoDB
1. Definition
A collection in MongoDB is a group of documents. It is similar to a table in SQL, but it does not enforce a fixed schema, meaning each document in a collection can have a different structure.
2. When to Use Collection
- When grouping similar types of data
- When storing multiple documents (records)
- When building scalable applications
- When data structure may vary between records
3. Where it is Used
- Inside a MongoDB database
- Web applications (users, products, orders)
- Backend APIs
- Real-time and scalable systems
4. Why We Use Collections
- Organizes data into logical groups
- Supports flexible document structures
- Improves data management
- Allows efficient querying and indexing
5. How Collection Works
- Stores multiple documents
- Documents inside can have different structures
- Automatically created when inserting data
- Supports indexing for fast queries
Basic Syntax
db.users.insertOne({
name: "Manaswini",
age: 22
});Real Example
// Collection: users
{
name: "Manaswini",
age: 22
}
{
name: "John",
email: "john@example.com"
}6. Explanation
- A collection stores multiple documents
- Documents can have different fields
- No fixed schema is required
- Similar to a table but more flexible
7. Advantages
- Flexible structure
- Easy to scale
- Supports large data
- Efficient querying with indexes
8. Disadvantages
- No strict schema enforcement
- Data inconsistency may occur
- Harder to maintain relationships
Interview Points
- Collection = group of documents
- Equivalent to table in SQL
- Schema-less (flexible structure)
- Stores related data together