Mongodb: object id as short primary key in collection

What is the best way to use objectId to generate using MOngoDB. I am not an expert, but so far I have created a separate identifier for my object (userid, postid), etc., because the object identifier is too long and makes the URL ugly if you use it as the main identifier. I keeo _id intact, as it helps indexing etc. I was interested to learn about some better strategy so that I could use mongo objectId as a more user friendly and easy to remember key. I read the key, this is a combination of dates, etc. Therefore, any part can be used uniquely in the collection for this purpose.

thanks,
BSR /

+6
source share
2 answers

If you have an existing ID (say from an existing dataset), then it is great for overriding _id with the one you have.

... keeo _id is untouched as it helps indexing etc.

MongoDB by default indexes the _id field. If you start nesting integers in the _id field, they will be indexed like everything else.

Thus, most RDBMs provide the identifier "auto-increment". This is good for small datasets, but really bad in terms of scalability. If you are trying to insert data on 20 servers at the same time, how do you save "auto-increment"?

The usual answer is that you are not doing this. Instead, you end up using the same GUIDs for these identifiers. In the case of MongoDB, an ObjectId is already specified.

I was interested to learn about some better strategy so that I could use the mongoId object as a more user-friendly and easy-to-remember key

Thus, the problem is that the identifier “easy to remember” is not actually associated with a “highly scalable database”. When you have a billion documents, identifiers are not really "easy to remember."

So you have to compromise here. If you have a table that can get really big, I suggest using ObjectId. If you have a table that is relatively small and not frequently updated (for example, the “lookup” table), you can create your own auto-increment.

The choice is really up to you.

+3
source

You can overwrite _id yourself. There is no obligation to use an object identifier with a generator. What is the problem with overriding _id inside your application to suit your needs?

0
source

Source: https://habr.com/ru/post/886625/


All Articles