Difference between id and _id fields in MongoDB

Is there a difference between using a field identifier or _ID from a MongoDB document?

I ask this because I usually use "_id", however I saw this view ({id: -1}) in the documentation: http://www.mongodb.org/display/DOCS/Optimizing+Object+IDs# OptimizingObjectIDs-Sortbyidtosortbyinsertiontime

EDIT

Turns out the documents were wrong.

+47
mongodb mongoid
Mar 14 2018-12-12T00:
source share
4 answers

I expect this to be just a typo in the documentation. The _id field is the primary key for each document. It is called _id , and is also accessible through id . Attempting to use the id key may result in an illegal ObjectId format error.

This section simply indicates that automatically generated ObjectIDs start with a timestamp so that you can sort your documents automatically. This is pretty cool since _id automatically indexed in every collection. See http://www.mongodb.org/display/DOCS/Object+IDs for more details. In particular, in the section "BSON Object Specification".

The BSON object identifier is a 12-byte value consisting of a 4-byte timestamp (seconds from the epoch), a three-byte machine identifier, a two-byte process identifier, and a 3-byte counter. Note that the timestamp and counter fields must be stored in a large endian, unlike other BSONs.

+41
Mar 14 '12 at 1:14
source share

The _id field is the default field for the Bson ObjectId and is indexed by default.

_id and id do not match. You can also add a field called id if you want, but it will not be an index unless you add an index.

This is just a typo in the documents.

+10
Mar 14 '12 at 1:15
source share

id is an alias for _id in mongoid.id, which returns the _id of the document. https://github.com/mongodb/mongoid/blob/master/lib/mongoid/fields.rb#L47

If the _id field is not specified, an ObjectedId object is created automatically.

+1
Aug 29 '16 at 12:45
source share

My two cents:

Field _id

MongoDB assigns the _id field _id each document and assigns a primary index on it. There are ways in which we can use secondary indexes. By default, MongoDB creates values ​​for the _id field of type ObjectID . This value is defined in the BSON spec and structured as follows:

ObjectID (12 bytes HEX string) = Date (4 bytes, timestamp value representing the number of seconds since the Unix era) + MAC address (3 bytes) + PID (2 bytes) + Counter (3 bytes)

0
Aug 29 '16 at 18:52
source share



All Articles