Difference between "id" and "_id" fields in MongoDB

MongodbMongoid

Mongodb Problem Overview


Is there any difference between using the field ID or _ID from a MongoDB document?

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

EDIT

Turns out the docs were wrong.

Mongodb Solutions


Solution 1 - Mongodb

I expect it's just a typo in the documentation. The _id field is primary key for every document. It's called _id and is also accessible via id. Attempting to use an id key may result in a illegal ObjectId format error.

That section is just indicating that the automatically generated ObjectIDs start with a timestamp so it's possible to sort your documents automatically. This is pretty cool since the _id is automatically indexed in every collection. See http://www.mongodb.org/display/DOCS/Object+IDs for more information. Specifically under "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.

Solution 2 - Mongodb

The _id field is the default field for Bson ObjectId's and it is,by default, indexed.

_id and id are not the same. You may also choose to add a field called id if you want, but it will not be index unless you add an index.

It is just a typo in the docs.

Solution 3 - Mongodb

id is an alias for _id in mongoid.id would return 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 is generated automatically.

Solution 4 - Mongodb

My two cents:

The _id field

MongoDB assigns an _id field to each document and assigns primary index on it. There're ways by which we can apply secondary indices as well. By default, MongoDB creates values for the _id field of type ObjectID. This value is defined in BSON spec and it's structured this way:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArthur NevesView Question on Stackoverflow
Solution 1 - MongodbLeonard GarveyView Answer on Stackoverflow
Solution 2 - MongodbBryan MigliorisiView Answer on Stackoverflow
Solution 3 - MongodbtessieView Answer on Stackoverflow
Solution 4 - MongodbxameeramirView Answer on Stackoverflow