What is better to choose a field for the primary key in MongoDB?
We need to implement a web application for MongoDB. One of the nuances with which I was faced, was the primary key in the document. MongoDB, by default, offers its a unique field "_id" which in most cases satisfies all the needs. But when designing a REST API, for example a request to the address "/users/574e7d2d8c772c53d12200d5", do not look, I want something like this "/users/id000000001" or "/users/1".
There is a need to choose, or take advantage of the recommendations in the official documentation, which describes two options (counter and loop), or create a custom field (something like "userID" or "id") with your user-defined functions. In addition, the official documentation is not often mentioned that with a field "_id" in MongoDB will feel better at operations, and scaling, so I want to give convenience without sacrificing performance.
How better to get out of this situation, or maybe there is already a "good practice" about this (I searched the Internet, but specific solutions are not seen)? Maybe you should leave the automatic box for internal use MongoDB, and add to this additional document, which is just the same will happen to the sample?
2 answers
Nothing prevents you to use your keys.
Mangovski put machine if you are not using any your key.
You can own a numbered identifier to write in the _id. But the ObjectId is faster*.
You can also do additional field and index.
Find more questions by tags MongoDB
If you need the original _id is not required, write in _id. - Bianka0 commented on July 8th 19 at 12:13