What data type is commonly used to store foreign key id in mongodb

What data type is the best way to store foreign key id in

mongodb? For example, in an article, if you want to store the user id, the foreign key id of the user, should you use the String type or the ObjectId type?

clipboard.png

Mar.03,2021

id any type is fine. Each data mongodb will automatically turn you into an objectid type of _ id,. You can also directly use _ id


try to use ObjectId, which has many advantages.
for example, if it contains time information, you can directly use ObjectId to sort by time.
for example, its rules support non-repetition of id generated in the same mongo cluster, so it is an efficient hash algorithm.
these things seem simple, but in fact, they are all big problems, especially distributed hash algorithms, which are not so easy to deal with. Try not to ask for trouble.


store foreign keys id this is based on business needs, but it is unique. You can use uuid or _ id field

, which is automatically produced by mongo .
Menu