Search code examples
c#mongodblinqfindunique

Why is mongo return zero matching document although there is one?


I have an app which asks users to pick up a username. I want to make all usernames unique so write something like that.

var uniqueUsername = false;
MongoPlayerData playerDB = new MongoPlayerData();
var nickCheck = Query.EQ("UserName", myUsername);
uniqueUsername = playerDB.PlayerInfo.Find(nickCheck).Count() == 0;
if(uniqueUsername){//Do something...}

This is the logic but some users can get the same username. How it is possible. Any idea ?


Solution

  • Could be since there is no constraint in place for that field/property in document and also MongoDB have no support for transaction (it just that it supports atomic operation). Thus, if you are inserting document on multiple threads then it's possible to have so. Instead you should try checking against the _id field to make sure the uniqueness of the document. If you really want to make sure that the UserName field must be unique across the documents likewise _id field then try creating a unique index on it.

    db.PlayerInfo.createIndex( { "UserName": 1 }, { unique: true } )