A MongoDB collection is a grouping of MongoDB documents that have no formal relationships; it can be thought of as the equivalent of a table in a relational database. However, there are several differences between a MongoDB collection and a relational database table, which I will outline below:
1. Schema: In a relational database, each table has a well-defined schema that defines the columns and their data types. Data in a table must adhere to this schema. In contrast, MongoDB collections do not follow a strict schema, which allows for greater flexibility in managing data. Documents within a collection can have different fields or different types for the same field.
2. Relationships: In a relational database, tables can be related to each other through foreign keys. MongoDB, on the other hand, employs a denormalized data model where related data is nested within a document, rather than being stored in separate tables. References and relationships can still be formed but they are not enforced by the database.
3. Querying: In a relational database, SQL is used to query data. In MongoDB, queries are written in JSON-like syntax that is easy to understand.
4. Scalability: Relational databases are typically vertically scalable, where you increase the resources of the server (such as adding more RAM or a faster CPU) to improve performance. MongoDB, on the other hand, is horizontally scalable, where you can add more nodes to a cluster to improve performance.
An example of a document in a MongoDB collection:
{
"_id" : ObjectId("5ec4058c1c90750c7643d3e4"),
"name": "John Doe",
"age": 32,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA",
"zip": "12345"
},
"interests": ["hiking", "reading", "traveling"]
}
In this example, there is no strict schema, and the document contains nested data and an array. In contrast, the equivalent relational database table would have defined columns with strict data types.