TIMEX
TIMEX

Reputation: 272374

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?

Upvotes: 11

Views: 8482

Answers (4)

Mario
Mario

Reputation: 1851

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

Upvotes: 13

SethO
SethO

Reputation: 2791

ObjectIds, if your primary method of data access, will be the fastest way to retrieve your stuff from MongoDB. We utilize our MongoDB as a keyed repository for most of our data access. You'll have great results doing what you're doing.

Upvotes: 3

kheya
kheya

Reputation: 7631

Index on _id field is auto created by mongo and default primary key. Speedwise, it will be super fast to access docs by _id field.

What concerns do you have?

Upvotes: 2

Karoly Horvath
Karoly Horvath

Reputation: 96326

_id is the primary key. It's indexed. Of course it's fast.

Upvotes: 5

Related Questions