A Glimpse of MongoDB
Document Model
MongoDB documents are displayed in JSON format, but stored in BSON.
Compared to JSON, BSON supports additional data types, like dates, numbers of various types and ObjectIds.
{
"_id": 1,
"name": "AC3 Phone",
"colors": ["black", "silver"],
"price": 200,
"available": true
}
ObjectId is a data type used to create unique identifiers for the required _id field.
Every document requires an id field, which acts as a primary key. If an inserted document doesn't include the _id field, MongoDB automatically generates an ObjectId for the _id field.
{
"_id": ObjectId("5c8eccc1caa187d17ca6ed16"),
"name": "chair",
"price": 25.00
}
Data Modeling
Data that is accessed together should be stored together.
Structure your data to match the ways that your application queries and updates it.
Types of Data Relationships
One-to-one
{ "_id": ObjectId("573a1390f29313caabcd413b"), "title": "Star Wars: Episode IV - A New Hope", "director": "George Lucas", "runtime": 121 }
One-to-many
{ "_id": ObjectId("573a1390f29313caabcd413b"), "title": "Star Wars: Episode IV - A New Hope", "cast": [ {"actor": "Mark Hamill", "character": "Luke Skywalker"}, {"actor": "Harrison Ford", "character": "Han Solo"}, {"actor": "Carrie Fisher", "character": "Princess Leia Organa"} ] }
Many-to-many
Ways to Model Relationships
Embedding
{ "_id": ObjectId("573a1390f29313caabcd413b"), "title": "Star Wars: Episode IV - A New Hope", "cast": [ {"actor": "Mark Hamill", "character": "Luke Skywalker"}, {"actor": "Harrison Ford", "character": "Han Solo"}, {"actor": "Carrie Fisher", "character": "Princess Leia Organa"} ] }
Referencing (Using reference is called linking or data normalization)
{ "_id": ObjectId("573a1390f29313caabcd413b"), "title": "Star Wars: Episode IV - A New Hope", "director": "George Lucas", "runtime": 121, "filming_locations": [ ObjectId("654a1420f29313fggbcd718"), ObjectId("654a1420f29313fggbcd719") ] }
Pro's and Con's of Embedding vs. Referencing
Drivers
When we run a Node.js application that connects to MongoDB, the application requires a set of libraries to interact with our MongoDB instance. These libraries are referred to as drivers. MongoDB provides a Node.js driver for asynchronous application code.