简体   繁体   中英

Get MongoDB collection by ObjectID

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM