MongoDB ObjectId function
Translation results:
object
英[ˈɒbdʒɪkt] US[ˈɑ:bdʒekt]
n.Object; target; object; object, object
vi .Disapprove, oppose; feel disgusted
vt. Put forward... reasons for objection
id
英[ɪd]
n.ID card; genetic quality; instinctive impulse; identifier
MongoDB ObjectId functionsyntax
Function: ObjectId is a 12-byte BSON type data with the following format: the first 4 bytes represent the timestamp and the next 3 bytes are the two words immediately following the machine identification code The stanza consists of the process id (PID) and the last three bytes are random numbers. Documents stored in MongoDB must have an "_id" key. The value of this key can be of any type, and the default is an ObjectId object. In a collection, each document has a unique "_id" value to ensure that each document in the collection can be uniquely identified. The main reason why MongoDB uses ObjectId instead of other more conventional methods (such as automatically increasing primary keys) is because it is laborious and time-consuming to automatically increase primary key values on multiple servers simultaneously.
MongoDB ObjectId functionexample
创建新的ObjectId 使用以下代码生成新的ObjectId: >newObjectId = ObjectId() 上面的语句返回以下唯一生成的id: ObjectId("5349b4ddd2781d08c09890f3") 你也可以使用生成的id来取代MongoDB自动生成的ObjectId: >myObjectId = ObjectId("5349b4ddd2781d08c09890f4") 创建文档的时间戳 由于 ObjectId 中存储了 4 个字节的时间戳,所以你不需要为你的文档保存时间戳字段,你可以通过 getTimestamp 函数来获取文档的创建时间: >ObjectId("5349b4ddd2781d08c09890f4").getTimestamp() 以上代码将返回 ISO 格式的文档创建时间: ISODate("2014-04-12T21:49:17Z") ObjectId 转换为字符串 在某些情况下,您可能需要将ObjectId转换为字符串格式。你可以使用下面的代码: >new ObjectId().str 以上代码将返回Guid格式的字符串:: 5349b4ddd2781d08c09890f3