Searching by ObjectId
In the legacy RDBMS world, developers are used to performing searches based on the primary key. In MongoDB, there is no concept of a primary key, as each document can be completely different from others, including having a completely different mix of fields. Accordingly, in order to keep the collection organized, MongoDB auto-generates an ObjectId instance. This is guaranteed to be unique among servers, replicas, and shards. It is created from the UNIX timestamp, a machine identifier, process ID, and a random value.
In order to perform a search based on this value, you can use the MongoDB\BSON\ObjectId class. To demonstrate how this works, let's work off the search we showed you previously. For illustration purposes, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access