Mongodb 数据库在分片配置中具有多个唯一索引
我在 mongodb 的数据库中有一个“用户”集合。我将使用分片。
除了标准 _id 之外,还有 3 个其他字段需要索引且唯一:用户名、电子邮件和帐号。所有这 3 个字段不一定对于每个用户文档都存在,在某些情况下根本不存在。
我希望对这些字段建立索引,因为用户将经常通过这些字段之一查找。我希望这些字段是唯一的,因为这是一个要求,我不想在客户端处理这个逻辑。
我知道 mongodb 确实有局限性,就像任何其他数据库一样,但我希望有一个解决方案,因为这是 Web 应用程序的相当常见的设置。
对于这种情况有一个优雅的解决方案吗?
不确定这对这个问题是否重要(因为这个问题与数据库结构有关),但我正在使用官方 mongodb C# 驱动程序。
I have a "users" collection in a database in mongodb. I will be using sharding.
Other than the standard _id, there are 3 other fields that need to be indexed and unique: username, email, and account number. All 3 of these fields will not necessarily exist for every user document, in some cases none will exist.
I'd like the fields to be indexed because users will be looked up frequently by one of these fields. I'd like the fields to be unique because this is a requirement and I'd rather not handle this logic client-side.
I understand that mongodb does have limitations, just like any other database, but I'm hoping there's a solution because this is a fairly common setup for web applications.
Is there an elegant solution for this scenario?
Not sure if it matters for this question (because the question pertains to database structure), but I am using the official mongodb C# driver.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Mongodb官方文档说,分片集合必须只有一个唯一索引,并且要求存在唯一字段。但它也说您还可以选择拥有其他独特的当且仅当分片键是其属性的前缀时才索引。因此您可以尝试此操作,但要注意,唯一键必须始终存在。
我不明白您的业务逻辑,其中不存在有关用户的信息。在这种情况下,您可以按
_id
进行分片并手动执行唯一性检查。Mongodb official documentation says, that sharded collection must have only one unique index, and requires the unique field(s) to exist. But it also says that you also have the option to have other unique indices if and only if the shard key is a prefix of their attributes. So you can try this, but aware, that unique key must always exist.
I don't understand your business logic where no information about the user would exist. In this case you can shard by
_id
and perform uniqueness checks manually.