Aquaboltar
Aquaboltar

Reputation: 1

Mongodb database with multiple unique indexes in sharded config

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.

Upvotes: 0

Views: 1736

Answers (1)

vissi
vissi

Reputation: 2334

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.

Upvotes: 3

Related Questions