Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How fast is it to look up by ObjectId in Mongodb?

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?

like image 366
TIMEX Avatar asked Jul 01 '11 19:07

TIMEX


People also ask

Is MongoDB ObjectId incremental?

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.

How fast is MongoDB search?

2. How fast are MongoDB queries? Pretty darn fast. Primary key or index queries should take just a few milliseconds.

How long is MongoDB ObjectId?

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.

Should I use MongoDB ObjectId?

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.


1 Answers

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).

like image 179
Mario Avatar answered Oct 16 '22 23:10

Mario