Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 965
Arthur Neves Avatar asked Mar 14 '12 00:03

Arthur Neves


People also ask

What is difference between ID and _id in mongoose?

From the documentation: Mongoose assigns each of your schemas an id virtual getter by default which returns the documents _id field cast to a string, or in the case of ObjectIds, its hexString.

What is _id field in MongoDB?

What Is MongoDB ObjectID? As MongoDB documentation explains, "ObjectIds are small, likely unique, fast to generate, and ordered." The _id field is a 12-byte Field of BSON type made up of several 2-4 byte chains and is the unique identifier/naming convention MongoDB uses across all its content.

Should I use _id in MongoDB?

You should NOT convert the ObjectId in the database to a string, and then compare it to another string. If you'd do this, MongoDB cannot use the _id index and it'll have to scan all the documents, resulting in poor query performance.

Is _id unique in MongoDB?

According to MongoDB's manual the answer is yes, it's unique by default: MongoDB creates the _id index, which is an ascending unique index on the _id field, for all collections when the collection is created. You cannot remove the index on the _id field.


2 Answers

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.

like image 186
Leonard Garvey Avatar answered Sep 17 '22 12:09

Leonard Garvey


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.

like image 41
Bryan Migliorisi Avatar answered Sep 19 '22 12:09

Bryan Migliorisi