Home  >  Q&A  >  body text

mongoDB修改"_id"的objectID到普通递增id为什么不好

以前学过sql,现在在学mongodb。看到objectID各种想把它改成和sql一样从1开始auto increment的id,我就全给update了。听说并不能这样做,还是要保留mongo原有的自动生成的obectID, 但是为什么?

滿天的星座滿天的星座2699 days ago552

reply all(2)I'll reply

  • ringa_lee

    ringa_lee2017-05-02 09:22:25

    It is actually easy to get the answer by analyzing the principle. Suppose you have a stack of numbers in your hand, from 1 to 100, as follows:

    1. A guy comes and asks you for a number, you give him one, that’s no problem.

    2. Two people arrived together and both asked you for a number. What should you do? Slowly come one by one, send out one after another. Slowly but it will be enough

    3. What should you do if 10 people come at the same time and ask you for your number? What about 100 people?

    Imagine the number of people coming as concurrent requests. It is not difficult to find that quickly allocating numbers has become a bottleneck. So self-increasing ID is actually not a good thing for RDBMS. But fortunately, traditional databases are stand-alone. They just add a lock to themselves to handle competition in the memory, so there is no big problem. MongoDB is a distributed database. Several machines need to coordinate with each other. You get 1, I get 2, and he gets 3. This lock needs to be coordinated through the network, which is very inefficient.
    Think about the purpose of distribution. One of them is to improve concurrency, so auto-incrementing IDs and high concurrency are actually contrary to each other. In a distributed environment, ensuring correct increment will inevitably affect efficiency. Besides, the self-increasing ID actually doesn’t have much advantage except that it looks cleaner, so it was inevitably abandoned. (Remember that ObjectID can actually be sorted, that is, the order of insertion time)

    reply
    0
  • ringa_lee

    ringa_lee2017-05-02 09:22:25

    https://docs.mongodb.com/v3.0/tutorial/create-an-auto-incrementing-field/#considerations

    Generally in MongoDB, you would not use an auto-increment pattern for the _id field, or any field, because it does not scale for databases with large numbers of documents. Typically the default value ObjectId is more ideal for the _id.

    文档上自己说,not scale for databases with large numbers of documents,自增的不适合有大数量documents的数据库

    reply
    0
  • Cancelreply