3
votes

I want to initiate the sharding. as you know shard key is very important. I found, MongoDB doesn't ensure unique _id field values when using a shard key other than _id.

In our collections, username shoud be shard key. If i create compound shard key and use _id as second part of shard key, does mongoDB guarantee uniqueness of _id ?

2
It will make sure that the username and _id combination is unique but not specifically the _idSammaye

2 Answers

2
votes

MongoDB does not ensure unique _id fields across shards when used as a compound key.

The documentation states :

MongoDB can enforce uniqueness for the shard key. For compound shard keys, MongoDB will enforce uniqueness on the entire key combination, and not for a specific component of the shard key.

So you if you want mongo to enforce uniqueness of the email, then simply use the email as the shard key.

An email address has some randomness, which is good (_id has some predictability built in), but I suggest you use the email field as a hashed shard key.

0
votes

MongoDB ensure uniqueness for all fields of a compound key. But I'm not sure if this is you are looking for. What happen if you have these documents ? {_id:12345,email:"[email protected]"} and {_id:4567,email:"[email protected]"}. The sharded key is unique, but you have the same email twice.

If you are looking for a unique email on all shards, you can try to create a proxy collection with an unique index.

You have more information here