Reputation: 1247
MongoDB IDs are unique for a single db cluster. Is it possible to get the collection a specific ObjectID is used in?
I have the hex representation of an ObjectID and need to know the collection the document with this ID is in. Possible?
Upvotes: 3
Views: 3370
Reputation: 18595
It's is not a native feature but it is possible by iterating over all collections (db.getCollectionNames())
and invoking a find({_id: <yourid>})
query. Obviously this will be a very slow operation so a schema change or using something other than ObjectId as your _id value is probably the way forward for you.
Upvotes: 4
Reputation: 18101
I'm not sure about your use case but if you are using ObjectID's for _id
the short answer is no.
A BSON ObjectID is a 12-byte value consisting of a 4-byte timestamp (seconds since epoch), a 3-byte machine id, a 2-byte process id, and a 3-byte counter [1]
Or diagrammatically:
|0 1 2 3 | 4 5 6 | 7 8 | 9 10 11 |
| time | machine | pid | inc |
So there is no collection information stored there.
However, any value can be used for _id
so you could use your own convention, which could store collection information if thats required...
[1] http://www.mongodb.org/display/DOCS/Object+IDs#ObjectIDs-TheBSONObjectIdDatatype
Upvotes: 2