Ute*_*007 26 c# mongodb mongodb-.net-driver
我与MongoDB共计n00b,我正在努力创造一个独特的领域EmailAddress.我已经在论坛中看到我必须创建一个索引,但到目前为止它对我来说并没有用.有人有代码示例吗?我是否必须在每次保存/调用时创建索引,还是只创建一次?
我试过这段代码:
DB.GetCollection<User>(Dbname)
.EnsureIndex(new IndexKeysBuilder()
.Ascending("EmailAddress"), IndexOptions.SetUnique(true));
DB.GetCollection<User>(Dbname).Save(user, SafeMode.True);
Run Code Online (Sandbox Code Playgroud)
我的User模型看起来像这样:
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; }
}
Run Code Online (Sandbox Code Playgroud)
Chr*_*tow 28
只需创建一次唯一索引,之后包含重复电子邮件地址的任何文档插入都将失败.这是一个例子:
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 = "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);
}
Run Code Online (Sandbox Code Playgroud)
ken*_*ust 22
根据C#mongo驱动程序2.0版规范,不推荐使用EnsureIndex():http://api.mongodb.org/csharp/current/html/M_MongoDB_Driver_MongoCollection_EnsureIndex_2.htm
继承人如何做异步和通过2.0代码:
var mongoClient = new MongoClient("connection");
var db = mongoClient.GetDatabase("database");
var options = new CreateIndexOptions() { Unique = true };
var field = new StringFieldDefinition<User>("EmailAddress");
var indexDefinition = new IndexKeysDefinitionBuilder<User>().Ascending(field);
await db.GetCollection<Users>("users").Indexes.CreateOneAsync(indexDefinition, options);
Run Code Online (Sandbox Code Playgroud)
你的代码看起来正确.这是一个完整运行的程序供您比较:
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<User>("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
}
}
}
Run Code Online (Sandbox Code Playgroud)
您还可以使用mongo shell确认索引已创建:
> 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
}
]
>
Run Code Online (Sandbox Code Playgroud)
从下面的 2.8 开始,是创建索引的方法。请注意最后两行。CreateOneAsync(indexDefinition, options)已过时。
var mongoClient = new MongoClient("connection");
var db = mongoClient.GetDatabase("database");
var options = new CreateIndexOptions() { Unique = true };
var field = new StringFieldDefinition<User>("EmailAddress");
var indexDefinition = new IndexKeysDefinitionBuilder<User>().Ascending(field);
var indexModel = new CreateIndexModel<User>(indexDefinition,options);
await db.GetCollection<Users>("users").Indexes.CreateOneAsync(indexModel);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21127 次 |
| 最近记录: |