Problem Statement
Explain the difference between a Document and a Collection in MongoDB.
Explanation
A document is the basic unit of data in MongoDB, similar to a row in a relational database. It is a JSON-like object stored as BSON that contains key-value pairs. Each document can have different fields and structures.
A collection is a group of documents, similar to a table in relational databases. The key difference is that collections are schema-less, meaning documents within the same collection can have completely different structures.
For example, one user document might have an email field while another might not. This flexibility makes MongoDB ideal for applications where data structures evolve over time.
Code Solution
SolutionRead Only
// Document example
{
_id: 1,
name: "Alice",
email: "alice@example.com"
}
// Another document in same collection
{
_id: 2,
name: "Bob",
phone: "123-456-7890"
}