Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to find a document in mongodb using object id alone (without knowing which collection)?

Tags:

mongodb

In MongoDB, object ID is quite likely unique across collections.

So is it possible to query a Mongo database for a document using the object ID alone, without knowing what collection it's in?

Thanks

like image 930
Zack Xu Avatar asked Oct 02 '22 17:10

Zack Xu


1 Answers

As you and @Sammaye is stating in the comments the ObjectID will likely be unique because (taken from the mongodb site)

ObjectId is a 12-byte BSON type, constructed using:

a 4-byte value representing the seconds since the Unix epoch,
a 3-byte machine identifier,
a 2-byte process id, and
a 3-byte counter, starting with a random value.

So it is pretty much impossible for it to be the same. (I can't seem to find if the 3-byte counter is the same across all collections or if there is a different one per collection)

For simplicity's sake lets say ObjectID is unique for every record in the database.

There is no "one query" that will search the whole database for the record. Mongodb has no default way to achieve what you are asking.

For a non-trivial solution see this question


Update after comment

if you don't care to query the database multiple times, you can

  • Query the database for all the collection names.
  • Iterate through all the collection names and using each name query each collection for that unique ObjectID
  • If a collection returns an object break the loop and return the object

(This is just descriptive of how to do it since you are not stating what programming language you are using to give you an example)

like image 125
Makis Tsantekidis Avatar answered Oct 07 '22 04:10

Makis Tsantekidis