Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: How to set another field (different from _id) as ID of mongo document?

Tags:

mongodb

nosql

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.

like image 663
Andrei Avatar asked Apr 06 '13 18:04

Andrei


People also ask

What is difference between id and _id in MongoDB?

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.

Can we override _id in MongoDB?

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.

What is the difference between id and _id in mongoose?

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

Is ID unique in MongoDB?

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


2 Answers

MongoDB requires the _id property as the unique primary key that it automatically indexes.

You have two options:

  1. Use the _id property and set it with the username.
  2. Create a username property, then add an index on that new property. You will still have the _id, but can query using the username.
like image 132
Serge Avatar answered Sep 20 '22 05:09

Serge


_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.

like image 31
RamBen Avatar answered Sep 19 '22 05:09

RamBen