ObjectId

ObjectId is a special data type for MongoDB. Every document has an _id field from cradle to grave. It is the primary key for each document in a collection and has to be unique. If we omit this field in a create statement, it will be assigned automatically with an ObjectId.

Messing with ObjectId is not advisable but we can use it (with caution!) for our purposes.

ObjectId has the following distinctions:

  • It has 12 bytes
  • It is ordered
  • Sorting by _id will sort by creation time for each document
  • Storing the creation time can be accessed by .getTimeStamp() in the shell

The structure of an ObjectId has the following:

  • A 4-byte value representing the seconds since the Unix epoch
  • A 3-byte machine identifier
  • A 2-byte process ID
  • A 3-byte counter, starting with a random value

The  following diagram shows the structure of an ObjectID:

By its structure, ObjectId will be unique for all purposes; however, since this is generated on the client side, you should check the underlying library's source code to verify that implementation is according to specification.

In the next section, we will learn about modeling data for atomic operations.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset