用C#创建MongoDB的唯一键

用C#创建MongoDB的唯一键

本文介绍了用C#创建MongoDB的唯一键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我跟MongoDB的总的n00b,我打造成一个独特的领域 EmailAddress的。我已经看到了,我要创建一个索引论坛,但它并没有为我工作了这么远。有没有人有一个代码示例?我一定要创建每次储存/呼叫指数,抑或是足以只创建一次呢?



我试过这段代码:

  DB.GetCollection<使用者> (数据库),
.EnsureIndex(新IndexKeysBuilder()
.Ascending(EmailAddress的),IndexOptions.SetUnique(真));

DB.GetCollection<使用者>(数据库).Save(用户,SafeMode.True);



我的用户模型如下:

 公共类用户
{
[必需(的ErrorMessage =请输入电邮)]
公共字符串EmailAddress的{搞定;组; }

公众的ObjectId标识{搞定;组; }

公共字符串名字{获得;组; }
公共字符串名字{获得;组; }
}


解决方案

唯一索引只需要要创建一次,即包含重​​复的电子邮件地址会失败,任何文件插入后。这里有一个例子:

  VAR服务器= MongoServer.Create(mongodb的:// localhost的); 
变种DB = server.GetDatabase(的myapp);

变种的用户= db.GetCollection<使用者>(用户);

users.EnsureIndex(新IndexKeysBuilder()
.Ascending(EmailAddress的),IndexOptions.SetUnique(真));

变种USER1 =新用户{EmailAddress的[email protected]};
VAR用户2 =新用户{EmailAddress的[email protected]};


{
users.Save(USER1,WriteConcern.Acknowledged);
users.Save(用户2 WriteConcern.Acknowledged); //< - 抛出M​​ongoSafeModeException
}
赶上(MongoSafeModeException前)
{
Console.WriteLine(ex.Message);
}


I am a total n00b with MongoDB and 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; }
}
解决方案

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);
}

这篇关于用C#创建MongoDB的唯一键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 04:41