Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there an underscore in front of the MongoDb document id?

Tags:

mongodb

Why is there an underscore in front of the MongoDb document id ?

Why not call it "id" instead of "_id" ?

Is this part of a naming convention I'm not aware of ?

like image 978
standac Avatar asked Mar 18 '13 15:03

standac


People also ask

How does the value of underscore Id get assigned to a document?

_id is the primary key on elements in a collection; with it, records can be differentiated by default. _id is automatically indexed. Lookups specifying { _id: <someval> } refer to the _id index as their guide. Users can also override _id to something other than an ObjectID data type, if desired.

What is document ID MongoDB?

The _id Field In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field.

What is always first field of document?

The _id field is the first field of every document. The value of the _id field can be of any BSON type except arrays. The default value of the _id field is ObjectId.

Are MongoDB IDS unique?

By default, MongoDB generates a unique ObjectID identifier that is assigned to the _id field in a new document before writing that document to the database. In many cases the default unique identifiers assigned by MongoDB will meet application requirements.


1 Answers

You may notice that MongoDB has a lot of functions (in the shell) and fields that start with an understore as a designation that they are internal or special and not user provided.

If you have your own "ID" then you can store it as "id" and still use the provided-by-MongoDB _id field although you are not required to use the ObjectId that MongoDB generates - you could store your own natural primary key in the "_id" field which will have a unique index on it always.

like image 72
Asya Kamsky Avatar answered Sep 19 '22 09:09

Asya Kamsky