Can I use String as ID type for mongodb document?

前端 未结 5 2274
死守一世寂寞
死守一世寂寞 2021-02-18 17:11

I am using java/morphia to deal with mongodb. The default ObjectId is not very convenient to use from Java layer. I would like to make it a String type while keep the key genera

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-18 17:31

    You can use any type of value for an _id field (except for Arrays). If you choose not to use ObjectId, you'll have to somehow guarantee uniqueness of values (casting ObjectId to string will do). If you try to insert duplicate key, error will occur and you'll have to deal with it.

    I'm not sure what effect will it have on sharded cluster when you attempt to insert two documents with the same _id to different shards. I suspect that it will let you insert, but this will bite you later. (I'll have to test this).

    That said, you should have no troubles with _id = (new ObjectId).toString().

提交回复
热议问题