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

前端 未结 4 1644
無奈伤痛
無奈伤痛 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:41

    There's no guarantee whatsoever about ObjectId uniqueness across collections. Even if it's probabilistically very unlikely, it would be a very poor application design that relied on _id uniqueness across collections.

    One can easily test this in the mongo shell:

    MongoDB shell version: 1.6.5
    connecting to: test
    > db.foo.insert({_id: 'abc'})
    > db.bar.insert({_id: 'abc'})
    > db.foo.find({_id: 'abc'})
    { "_id" : "abc" }
    > db.bar.find({_id: 'abc'})
    { "_id" : "abc" }
    > db.foo.insert({_id: 'abc', data:'xyz'})
    E11000 duplicate key error index: test.foo.$_id_  dup key: { : "abc" }
    

    So, absolutely don't rely on _id's being unique across collections, and since you don't control the ObjectId generation function, don't rely on it.

    It's possible to create something that's more like a uuid, and if you do that manually, you could have some better guarantee of uniqueness.

    Remember that you can put objects of different "types" in the same collection, so why not just put your two "tables" in the same collection. They would share the same _id space, and thus, would be guaranteed unique. Switching from "prospective" to "registered" would be a simple flipping of a field...

提交回复
热议问题