Creating MongoDB Unique Key with C#

后端 未结 6 1573
故里飘歌
故里飘歌 2020-12-29 03:08

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 an

6条回答
  •  有刺的猬
    2020-12-29 04:08

    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("users");
    
    users.EnsureIndex(new IndexKeysBuilder()
        .Ascending("EmailAddress"), IndexOptions.SetUnique(true));
    
    var user1 = new User { EmailAddress = "joe@example.com" };
    var user2 = new User { EmailAddress = "joe@example.com" };
    
    try
    {
        users.Save(user1, WriteConcern.Acknowledged);
        users.Save(user2, WriteConcern.Acknowledged);  // <-- throws MongoSafeModeException
    }
    catch (MongoSafeModeException ex)
    {
        Console.WriteLine(ex.Message);
    }
    

提交回复
热议问题