我可以将String用作mongodb文档的ID类型吗? [英] Can I use String as ID type for mongodb document?

查看:475
本文介绍了我可以将String用作mongodb文档的ID类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用java/morphia处理mongodb.从Java层使用默认的ObjectId不太方便.我想使其成为String类型,同时保持使用ObjectId的密钥生成过程,例如_id = new ObjectId.toString().

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 generation process using ObjectId, say _id = new ObjectId.toString().

我想知道这样做是否有副作用?例如,它是否会以任何方式影响数据库性能或引起关键冲突?会影响分片环境吗?

I want to know if there is any side effects doing it this way? For example, will it impact the database performance or causing key conflicts in any means? Will it affect the sharding environment ...

推荐答案

您可以对_id字段使用任何类型的值(数组除外).如果选择不使用ObjectId,则必须以某种方式保证值的唯一性(将ObjectId广播到字符串中可以做到).如果您尝试插入重复的密钥,则会发生错误,因此您必须对其进行处理.

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.

当您尝试将具有相同_id的两个文档插入不同的分片时,我不确定分片群集会有什么影响.我怀疑它会让您插入,但是稍后会咬住您. (我必须对此进行测试).

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).

也就是说,_id = (new ObjectId).toString()应该没有问题.

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

这篇关于我可以将String用作mongodb文档的ID类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆