Mongodb 简明教程
MongoDB - ObjectId
在所有前面的章节中,我们一直在使用 MongoDB 对象 Id。在本章中,我们将了解 ObjectId 的结构。
We have been using MongoDB Object Id in all the previous chapters. In this chapter, we will understand the structure of ObjectId.
ObjectId 是一个 12 字节 BSON 类型,具有以下结构: −
An ObjectId is a 12-byte BSON type having the following structure −
-
The first 4 bytes representing the seconds since the unix epoch
-
The next 3 bytes are the machine identifier
-
The next 2 bytes consists of process id
-
The last 3 bytes are a random counter value
MongoDB 使用 ObjectId 作为每个文档的 _id 字段的默认值,该值是在创建任何文档时生成的。ObjectId 的复杂组合使所有 _id 字段都是唯一的。
MongoDB uses ObjectIds as the default value of _id field of each document, which is generated while the creation of any document. The complex combination of ObjectId makes all the _id fields unique.
Creating New ObjectId
若要生成一个新的 ObjectId,请使用以下代码: −
To generate a new ObjectId use the following code −
>newObjectId = ObjectId()
上面的语句返回了以下唯一生成的 id: −
The above statement returned the following uniquely generated id −
ObjectId("5349b4ddd2781d08c09890f3")
除了让 MongoDB 生成 ObjectId 外,您还可以提供一个 12 字节的 id: −
Instead of MongoDB generating the ObjectId, you can also provide a 12-byte id −
>myObjectId = ObjectId("5349b4ddd2781d08c09890f4")
Creating Timestamp of a Document
由于 _id ObjectId 默认存储 4 字节的时间戳,因此在大多数情况下,您不需要存储任何文档的创建时间。您可以使用 getTimestamp 方法获取文档的创建时间: −
Since the _id ObjectId by default stores the 4-byte timestamp, in most cases you do not need to store the creation time of any document. You can fetch the creation time of a document using getTimestamp method −
>ObjectId("5349b4ddd2781d08c09890f4").getTimestamp()
这将以 ISO 日期格式返回此文档的创建时间: −
This will return the creation time of this document in ISO date format −
ISODate("2014-04-12T21:49:17Z")
Converting ObjectId to String
在某些情况下,您可能需要 ObjectId 在字符串格式中的值。若要将 ObjectId 转换为字符串,请使用以下代码: −
In some cases, you may need the value of ObjectId in a string format. To convert the ObjectId in string, use the following code −
>newObjectId.str
上面的代码将返回 Guid 的字符串格式: −
The above code will return the string format of the Guid −
5349b4ddd2781d08c09890f3