English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
在前面的章节中,我们一直在使用MongoDB对象Id。在本章中,我们将了解ObjectId的结构。
ObjectId是一个12字节的 BSON 类型,具有以下结构-
前4个字节表示自 unix 新纪元以来的秒数
接下来的3个字节是机器标识符
接下来的2个字节由进程 id 组成
最后3个字节是一个随机计数器值
MongoDB使用ObjectIds作为_id
每个文档字段的默认值,该默认值是在创建任何文档时生成的。ObjectId的复杂组合使所有_id字段唯一。
要生成新的ObjectId,请使用以下代码-
>newObjectId = ObjectId()
上面的语句返回以下唯一生成的id-
ObjectId("5349b4ddd2781d08c09890f3")
In addition to providing MongoDB-generated ObjectIds, you can also provide12Byte ID-
>myObjectId = ObjectId("5349b4ddd2781d08c09890f4")
Since _id ObjectId is stored by default4Byte timestamp, so in most cases, you do not need to store the creation time of any document. You can use the getTimestamp method to get the creation time of the document-
>ObjectId("5349b4ddd2781d08c09890f4).getTimestamp()
This will return the creation time of this document in ISO date format-
ISODate("2014-04-12T21:49:17Z")
In some cases, you may need a string representation of the ObjectId value. To convert ObjectId to string, use the following code-
>newObjectId.str
The following code will return the Guid in string format-
5349b4ddd2781d08c09890f3