I'm looking up ObjectIds everywhere, as if they're cake.
Is this OK? _id
fields are supposed to be looked up like crazy, right?
MongoDB does not have out-of-the-box auto-increment functionality, like SQL databases. By default, it uses the 12-byte ObjectId for the _id field as the primary key to uniquely identify the documents.
2. How fast are MongoDB queries? Pretty darn fast. Primary key or index queries should take just a few milliseconds.
ObjectId values are 12 bytes in length, consisting of: A 4-byte timestamp, representing the ObjectId's creation, measured in seconds since the Unix epoch. A 5-byte random value generated once per process. This random value is unique to the machine and process.
You should NOT convert the ObjectId in the database to a string, and then compare it to another string. If you'd do this, MongoDB cannot use the _id index and it'll have to scan all the documents, resulting in poor query performance. Show activity on this post. Don't.
A more precise answer: MongoDB uses B-Tree indexes. Searching for a particular value in a B-Tree has O(log n) complexity in the average and worst case, which can be considered reasonably fast (i.e. a binary search). It is not constant complexity = O(1) though, so you still might have some slowdown effects if the index size grows larger than available RAM. (MongoDB tries to keep the indexes in RAM, and every IO needed to look up an index on disk will slow down your query considerably).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With