Database Reference
In-Depth Information
Creating the _id Field
Every object within the MongoDB database contains a unique identifier to distinguish
that object from every other object. This identifier is called the _ id key, and it is added
automatically to every document you create in a collection.
The _id key is the first attribute added in each new document you create. This
remains true even if you do not tell MongoDB to create the key. For example, none of the
code in the preceding examples used the _id key. Nevertheless, MongoDB created an _id
key for you automatically in each document. It did so because _id key is a mandatory
element for each document in the collection.
If you do not specify the _id value manually, the type will be set to a special BSON
datatype that consists of a 12-byte binary value. Thanks to its design, this value has
a reasonably high probability of being unique. The 12-byte value consists of a 4-byte
timestamp (seconds since epoch, or January 1 st , 1970), a 3-byte machine ID, a 2-byte
process ID, and a 3-byte counter. It's good to know that the counter and timestamp fields
are stored in Big Endian format. This is because MongoDB wants to ensure that there is an
increasing order to these values, and a Big Endian approach suits this requirement best.
the terms Big Endian and Little Endian refer to how individual bytes/bits are
stored in a longer data word in the memory. Big endian simply means that the most
significant value is saved first. Similarly, little endian means that the least significant value
is saved first.
Note
Figure 3-3 shows how the value of the _id key is built up and where the values
come from.
012345678910 11
Time
machinePid inc
Figure 3-3. Creating the _id key in MongoDB
Every additional supported driver that you load when working with MongoDB
(such as the PHP driver or the Python driver) supports this special BSON datatype and
uses it whenever new data is created. You can also invoke ObjectId() from the MongoDB
shell to create a value for an _id key. Optionally, you can specify your own value by using
ObjectId( string ) , where string represents the specified hex string.
 
Search WWH ::




Custom Search