A document is a representation of a single entity of data in a MongoDB database. A collection is made up of one or more related objects. There is a major difference between MongoDB and SQL in that MongoDB documents are very different from SQL rows. Row data is very flat, meaning there is one column for each value in the row. However, in MongoDB, documents can contain embedded subdocuments, thus providing a much closer inherent data model to your applications.
In fact, the records in a MongoDB database that represent documents are stored as BSON, which is a lightweight binary form of JSON. In addition, MongoDB field/value pairs correspond to JavaScript property/value pairs. These field/value pairs define the values that are stored in the document. This means there is very little translation necessary to convert MongoDB records back into the JavaScript objects that you will use in your Node.js applications.
For example, a document in MongoDB may be structured like this, with name
, version
, languages
, admin
, and paths
fields:
{
name: "New Project",
version: 1,
languages: ["JavaScript", "HTML", "CSS"],
admin: {name: "Brad", password: "****"},
paths: {temp: "/tmp", project:"/opt/project", html: "/opt/project/html"}
}
Notice that the document structure contains fields/properties that are strings, integers, arrays, and objects, just like in a JavaScript object. Table 11.1 lists the different data types that field values can be set to in a BSON document.
The fieldnames cannot contain null
characters, dots (.), or dollar signs ($
). Also, the _id
fieldname is reserved for the object ID. The _id
field is a unique ID for the system that is made up of the following parts:
A 4-byte value representing the seconds since the last epoch
A 3-byte machine identifier
A 2-byte process ID
A 3-byte counter, starting with a random value
The maximum size of a document in MongoDB is 16MB. This prevents queries that result in an excessive amount of RAM being used or intensive hits to the file system. Although you may never come close to this number, you need to keep the maximum document size in mind when designing some complex data types that contain file data.