Creating MongoDB Unique Key with C#

后端 未结 6 1652
故里飘歌
故里飘歌 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:56

    Your code looks right. Here's a full running program for you to compare against:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    using MongoDB.Bson;
    using MongoDB.Driver;
    using MongoDB.Driver.Builders;
    
    namespace TestEnsureIndexOnEmailAddress {
        public class User {
            public ObjectId Id;
            public string FirstName;
            public string LastName;
            public string EmailAddress;
        }
    
        public static class Program {
            public static void Main(string[] args) {
                var server = MongoServer.Create("mongodb://localhost/?safe=true");
                var database = server["test"];
                var users = database.GetCollection("users");
                if (users.Exists()) { users.Drop(); }
    
                users.EnsureIndex(IndexKeys.Ascending("EmailAddress"), IndexOptions.SetUnique(true));
                var john = new User { FirstName = "John", LastName = "Smith", EmailAddress = "jsmith@xyz.com" };
                users.Insert(john);
                var joe = new User { FirstName = "Joe", LastName = "Smith", EmailAddress = "jsmith@xyz.com" };
                users.Insert(joe); // should throw exception
            }
        }
    }
    

    You can also use the mongo shell to confirm that the index got created:

    > db.users.getIndexes()
    [
            {
                    "name" : "_id_",
                    "ns" : "test.users",
                    "key" : {
                            "_id" : 1
                    },
                    "v" : 0
            },
            {
                    "_id" : ObjectId("4de8152ee447ad2550e3b5fd"),
                    "name" : "EmailAddress_1",
                    "ns" : "test.users",
                    "key" : {
                            "EmailAddress" : 1
                    },
                    "unique" : true,
                    "v" : 0
            }
    ]
    >
    

提交回复
热议问题