简体   繁体   English

通过ObjectID获取MongoDB集合

[英]Get MongoDB collection by ObjectID

MongoDB IDs are unique for a single db cluster. MongoDB ID对于单个数据库集群是唯一的。 Is it possible to get the collection a specific ObjectID is used in? 是否有可能在集合中使用特定的ObjectID?

I have the hex representation of an ObjectID and need to know the collection the document with this ID is in. Possible? 我有一个ObjectID的十六进制表示,需要知道具有此ID的文档的集合。可能吗?

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. 它不是本机功能,但可以通过遍历所有集合(db.getCollectionNames())并调用find({_id: <yourid>})查询来实现。 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. 显然,这将是一个非常慢的操作,因此架构更改或使用除ObjectId之外的其他内容作为您的_id值可能是您的前进方向。

I'm not sure about your use case but if you are using ObjectID's for _id the short answer is no. 我不确定你的用例,但如果你使用ObjectID for _id ,简短的回答是否定的。

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] BSON ObjectID是一个12字节的值,包括一个4字节的时间戳(自纪元以来的秒数),一个3字节的机器ID,一个2字节的进程ID和一个3字节的计数器[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... 但是, 任何值都可以用于_id因此您可以使用自己的约定,如果需要,可以存储集合信息...

[1] http://www.mongodb.org/display/DOCS/Object+IDs#ObjectIDs-TheBSONObjectIdDatatype [1] http://www.mongodb.org/display/DOCS/Object+IDs#ObjectIDs-TheBSONObjectIdDatatype

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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