MongoDB Primary Keys Are Your Friend

All documents in a MongoDB collection have a primary key dubbed _id. This field is automatically assigned to a document upon insert, so there’s rarely a need to provide it. What’s interesting about the _id field is that it is time based. That is, the underlying type of _id, which is ObjectId, is a 12-byte BSON type, and 4 of those bytes represent the seconds since Unix epoch.

What’s also special about the _id field is that it is automatically indexed as you can see below by calling getIndexes on any collection.

All MongoDB collections have an _id field as an index:
 

> db.things.getIndexes()[     {          "v" : 1,          "key" : {               "_id" : 1          },          "ns" : "test.things",          "name" : "_id_"     }]

Source : http://www.javacodegeeks.com/2013/06/mongodb-primary-keys-are-your-friend.html

Back to Top