N
N
Nicholas Lindemann2016-06-25 13:54:34
MongoDB
Nicholas Lindemann, 2016-06-25 13:54:34

What is the best field to choose for primary key in MongoDB?

You need to implement a web application on MongoDB. One of the nuances that I encountered was the primary key in the document. MongoDB provides its own unique "_id" field by default, which in most cases fulfills all needs. But when developing a REST API, for example, a call to the address "/users/574e7d2d8c772c53d12200d5" does not look at all, I want something like this "/users/id000000001", or this "/users/1".
There is a need to choose, either use the recommendations in the official documentation, which describes two options (counter and loop), or create your own field (something like "userID", or "id") with your own user functions. In addition, the official documentation mentions more than once that it is with the "_id" field that MongoDB will feel best, both during operations and when scaling, so I want to endow it with convenience without sacrificing performance.
What is the best way to get out of this situation, or maybe there is already a "good practice" in this regard (I searched on the Internet, but did not see specific solutions)? It may be worth leaving the automatic field for MongoDB internal needs, and adding an additional one to this document,

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
VekaVeka, 2016-06-25
@VekaVeka

Nobody is stopping you from using your keys.
Mongolian is set automatically if you do not use any of your keys.

L
lega, 2016-06-25
@lega

You can write your numbered identifier in _id. But ObjectId is faster*.
You can also make an additional field and index.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question