Luis,
In regards to the example that you gave. If you create a unique compound index, individual keys can have the same values, but the combination of values across the keys that exist in the index entry can only appear once. So if we had a unique index on {"username" : 1, "role" : 1}
. The following inserts would be legal:
> db.users.insert({"username" : "Luis Sieira"})
> db.users.insert({"username" : "Luis Sieira", "role" : "regular"})
> db.users.insert({"username" : "Luis Sieira", "role" : "admin"})
If you tried to insert a second copy of any of the above documents, you would cause a duplicate key exception.
Your Scenarios
I think that if you added an allowance
field to your schema. When you do inserts for admins for new accounts. You can add a different value for their admin allowance. If you added unique index for {"username":1,"email":1, "allowance" : 1}
You could make the following inserts, legally:
>db.users.insert({"username" : "inspired","email": "i@so.com", "allowance": 0})
>db.users.insert({"username" : "inspired","email": "i@so.com", "allowance": 1})
>db.users.insert({"username" : "inspired","email": "i@so.com", "allowance": 2})
>db.users.insert({"username" : "inspired","email": "i@so.com", "allowance": 3})
Of course, you'll have to handle certain logic from the client, but this will allow you to use an allowance code of 0
for regular
accounts and then allow you to save a higher allowance code (incrementing it or adding custom value for it) each time an admin
creates another account.
I hope this offers some direction with using unique compound indexes.