For example, what if I would like to have Username as unique ID of my mongo document instead of having default "_id"?
I'd like to achieve this using mongo.exe console.
The _id field in MongoDB document database is considered to be the default field for BSON ObjectId's and it is, by default, indexed. _id and id are not the same. You may also prefer to add a field called id if you want, but it will not be index unless you add an index.
The _id field is immutable—that is, once a document exists in your MongoDB system, it has, by definition, been assigned an _id, and you cannot change or update its primary key. That said, _id can be overridden when you insert new documents, but by default it will be populated with an ObjectID.
So, basically, the id getter returns a string representation of the document's _id (which is added to all MongoDB documents by default and have a default type of ObjectId ). Regarding what's better for referencing, that depends entirely on the context (i.e., do you want an ObjectId or a string ).
MongoDB uses ObjectIds as the default value of _id field of each document, which is generated during the creation of any document. Object ID is treated as the primary key within any MongoDB collection. It is a unique identifier for each document or record. Syntax: ObjectId(<hexadecimal>).
MongoDB requires the _id property as the unique primary key that it automatically indexes.
You have two options:
_id
is important in replication. You can create a collection without an _id
index, but you will never be able to replicate the database. Replication requires the _id
index on every collection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With