Difference between “id” and “_id” fields in MongoDB

前端 未结 4 1224
南笙
南笙 2020-11-30 02:01

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})

4条回答
  •  天命终不由人
    2020-11-30 02:57

    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.

提交回复
热议问题