Mongodb Guide (translated) (xiii)-developer zone-Object ID for data types and conventions (II)

Source: Internet
Author: User
Tags findone
Object IDs

Documents in mongodb must be identified by a unique keyword _ id.

_ Id field

Almost every mongodb document uses the _ id field as the first attribute (with some exceptions in the system set and Capacity Set (capped collection ). The _ id value can be of any type. The most common practice is to use the ObjectId type. The _ id field of each document must be unique in this set. This is mandatory because the set automatically creates an index for _ id (except those mentioned earlier ).

If you try to insert a document without the _ id field, the database automatically generates an object id and stores it in the _ id field.

The _ id value can be of any type, as long as it is unique, except for arrays. If your document has a unique and unchangeable primary key, we recommend that you use it instead of the automatically generated _ id. Arrays are not allowed as _ IDs because they are multi-key.

BSON ObjectId Data Type

Although the _ id value can be of any type, mongodb still provides a special BSON data type for the Object id. This type is designed as a binary value of 12 bytes, so that it has a very high probability to ensure the uniqueness of the allocation. All officially supported mongodb drivers use this type as the _ id value by default. At the same time, when the mongo database itself inserts a document without the _ id field, it also uses this type to assign a value to _ id.

In mongodb shell, ObjectId () can create an object ID using the specified hexadecimal String in ObjectIds. ObjectId (String.

> x={ name: "joe" }
{ name : "joe" }
> db.people.save(x)
{ name : "joe" , _id : ObjectId( "47cc67093475061e3d95369d" ) }
> x
{ name : "joe" , _id : ObjectId( "47cc67093475061e3d95369d" ) }
> db.people.findOne( { _id: ObjectId( "47cc67093475061e3d95369d" ) } )
{ _id : ObjectId( "47cc67093475061e3d95369d" ) , name : "joe" }
> db.people.findOne( { _id: new ObjectId( "47cc67093475061e3d95369d" ) } )
{ _id : ObjectId( "47cc67093475061e3d95369d" ) , name : "joe" }

BSON ObjectID description

A bson ObjectID is a 12-byte value that contains a 4-byte timestamp (the number of seconds since the epoch), a 3-byte machine id, a 2-byte process id, and a 3-Byte Count value. Note that, unlike other fields in BSON, the timestamp and calculated value fields must be stored as big endian. This is because they are compared by byte, and we want to ensure that they are in ascending order in most cases. Its format:

0 1 2 3 4 5 6 7 8 9 10 11
Time Machine Pid Inc

 

 

  • TimeStamp. This is a unix-style TimeStamp. It is a signed integer that represents the number of seconds since or before January 1, January 1, 1970.
  • Machine. It is the hash (md5) value of the host name, the mac/network address, or the first three bytes of the Virtual Machine id.
  • Pid. It is a two-byte process id (or thread id) generated by the process ).
  • Increment. This is an auto-increment value, or the random value of the counter cannot be used in the current language/runtime.

BSON ObjectIds can be any unique 12-byte binary string. However, the server itself and most drivers use the above format.

Sequence Number

Traditional databases often use ascending sequence numbers as primary keys. In MongoDB, the better way is to use Object IDs. This concept means that in a very large cluster, creating an Object ID is much easier than maintaining the global sequence number, which increases monotonically.

However, sometimes you still need a sequence number. You can create a "counter" document and use the findAndModify command to achieve this purpose.

function counter(name) {
var ret = db.counters.findAndModify({query:{_id:name}, update:{$inc : {next:1}}, "new":true,
upsert:true});
// ret == { "_id" : "users", "next" : 1 }
return ret.next;
}
db.users.insert({_id:counter("users"), name:"Sarah C."}) // _id : 1
db.users.insert({_id:counter("users"), name:"Bob D."}) // _id : 2
//repeat

UUIDs

The _ id field can be of any type, but must be unique. In this way, you can use UIDs in the _ id field to replace BSON ObjectIds (BSON ObjectIds should be lightweight; they do not need to be globally unique, and they can only be unique in the current database cluster ). when using UUIDs, your application must generate the UUID by itself. considering the efficiency, it is ideal to store UUID as the [DOCS: BSON] type-in any case you can still insert it as a hexadecimal string, if you know that space and speed are not a problem at this time.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.