Object IDs

Object IDs

Documents in MongoDB required a key, _id, which uniquely identifies them.(只有_id建立索引之后,各个doc的_id才会不同,否则有可能相同)

The _id Field

If a user tries to insert a document without providing an _id field, the database will automatically generate an _object id_ and store it the _id field.(当客户端提供不提供_id时,则服务器来产生。)

The _id value may be of any type, other than arrays, so long as it is a unique. If your document has a natural primary key that is immutable we recommend you use that in _id instead of the automatically generated ids. Arrays are not allowed _ids because they areMultikeys.

The BSON ObjectId Datatype

 a special BSON datatype is provided for object ids.  All of the officially-supported MongoDB drivers use this type by default for _id values.  Also, the Mongo database itself uses this type when assigning _id values on inserts where no _id value is present.

In the MongoDB shell, ObjectId() may be used to create ObjectIds.  ObjectId(string) creates an object ID from the specified hex string.

BSON ObjectID Specification

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. Note that the timestamp and counter fields must be stored big endian(高字节在高位) unlike the rest of BSON. This is because they are compared byte-by-byte and we want to ensure a mostly increasing order. The format:

0 1 2 3 4 5 6 7 8 9 10 11
time machine pid inc

 the server itself and almost all drivers use the format above.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值