Creating MongoDB Unique Key with C#

后端 未结 6 1683
故里飘歌
故里飘歌 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 03:48

    EnsureIndex() is deprecated/obsolete per the C# mongo drivers version 2.0 spec: http://api.mongodb.org/csharp/current/html/M_MongoDB_Driver_MongoCollection_EnsureIndex_2.htm

    heres how to do it async and via 2.0 code:

    var mongoClient = new MongoClient("connection");
    var db = mongoClient.GetDatabase("database");
    
    var options = new CreateIndexOptions() { Unique = true };
    var field = new StringFieldDefinition("EmailAddress");
    var indexDefinition = new IndexKeysDefinitionBuilder().Ascending(field);
    await db.GetCollection("users").Indexes.CreateOneAsync(indexDefinition, options);
    

    In case of a non-string index:

       var options = new CreateIndexOptions() { Unique = true };
       IndexKeysDefinition keyCode = "{ Code: 1 }";
       var codeIndexModel = new CreateIndexModel(keyCode, options);
    

提交回复
热议问题