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

4

11

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?

Sleuth answered 1/7, 2011 at 19:36 Comment(2)
Surely this question is only meaningful if the look-up speed is relative to some other type of look-up, like an index on a string field, or an index on a unique string or integer field, or a non-indexed field?Priddy
Related: #18680962Priddy
B
5

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

Beaulahbeaulieu answered 1/7, 2011 at 19:40 Comment(2)
Why do you say 'primary' key? I don't believe there are primary and foriegn keys in Mongo, just indexes.Traweek
Technically, yes. From the glossary: "The _id field must have a unique value. You can think of the _id field as the document’s primary key."Beaulahbeaulieu
M
13

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

Manisa answered 1/7, 2011 at 20:7 Comment(2)
There is nothing like "constant complexity". The overall complexity is O(1). Point.Outhouse
true, the word "time" was missing after "constant".Manisa
B
5

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

Beaulahbeaulieu answered 1/7, 2011 at 19:40 Comment(2)
Why do you say 'primary' key? I don't believe there are primary and foriegn keys in Mongo, just indexes.Traweek
Technically, yes. From the glossary: "The _id field must have a unique value. You can think of the _id field as the document’s primary key."Beaulahbeaulieu
H
3

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.

Haynes answered 1/7, 2011 at 20:6 Comment(0)
C
2

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?

Cameroun answered 1/7, 2011 at 19:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.