Creating MongoDB Unique Key with C#

Uter1007 picture Uter1007 · Jun 2, 2011 · Viewed 25.4k times · Source

I am fighting to create a unique field EmailAddress. I've already seen in forums that I have to create an index, but it didn't work out for me so far. Does anyone have a code example? Do I have to create the index on every save/call, or is it enough to create it only once?

I tried this code:

DB.GetCollection<User>(Dbname)
    .EnsureIndex(new IndexKeysBuilder()
        .Ascending("EmailAddress"), IndexOptions.SetUnique(true));

DB.GetCollection<User>(Dbname).Save(user, SafeMode.True);

My User model looks like this:

public class User
{
    [Required(ErrorMessage = "Email Required")]
    public string EmailAddress { get; set; }

    public ObjectId Id { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Answer

Chris Fulstow picture Chris Fulstow · Jun 3, 2011

The unique index only needs to be created once, after that any document inserts that contain a duplicate email address will fail. Here's an example:

var server = MongoServer.Create("mongodb://localhost");
var db = server.GetDatabase("myapp");

var users = db.GetCollection<User>("users");

users.EnsureIndex(new IndexKeysBuilder()
    .Ascending("EmailAddress"), IndexOptions.SetUnique(true));

var user1 = new User { EmailAddress = "[email protected]" };
var user2 = new User { EmailAddress = "[email protected]" };

try
{
    users.Save(user1, WriteConcern.Acknowledged);
    users.Save(user2, WriteConcern.Acknowledged);  // <-- throws MongoSafeModeException
}
catch (MongoSafeModeException ex)
{
    Console.WriteLine(ex.Message);
}