Possibility of duplicate Mongo ObjectId's being generated in two different collections?

前端 未结 4 1645
無奈伤痛
無奈伤痛 2020-11-22 15:45

Is it possible for the same exact Mongo ObjectId to be generated for a document in two different collections? I realize that it\'s definitely very unlikely, but is it possi

4条回答
  •  悲&欢浪女
    2020-11-22 16:49

    In case anyone is having problems with duplicate Mongo ObjectIDs, you should know that despite the unlikelihood of dups happening in Mongo itself, it is possible to have duplicate _id's generated with PHP in Mongo.

    The use-case where this has happened with regularity for me is when I'm looping through a dataset and attempting to inject the data into a collection.

    The array that holds the injection data must be explicitly reset on each iteration - even if you aren't specifying the _id value. For some reason, the INSERT process adds the Mongo _id to the array as if it were a global variable (even if the array doesn't have global scope). This can affect you even if you are calling the insertion in a separate function call where you would normally expect the values of the array not to persist back to the calling function.

    There are three solutions to this:

    1. You can unset() the _id field from the array
    2. You can reinitialize the entire array with array() each time you loop through your dataset
    3. You can explicitly define the _id value yourself (taking care to define it in such a way that you don't generate dups yourself).

    My guess is that this is a bug in the PHP interface, and not so much an issue with Mongo, but if you run into this problem, just unset the _id and you should be fine.

提交回复
热议问题