2011-06-02 17 views
22

Sono un n00b totale con MongoDB e sto lottando per creare un campo unico EmailAddress. Ho già visto nei forum che devo creare un indice, ma finora non ha funzionato per me. Qualcuno ha un esempio di codice? Devo creare l'indice su ogni salvataggio/chiamata, o è sufficiente crearlo solo una volta?Creazione della chiave univoca MongoDB con C#

Ho provato questo codice:

DB.GetCollection<User>(Dbname) 
    .EnsureIndex(new IndexKeysBuilder() 
     .Ascending("EmailAddress"), IndexOptions.SetUnique(true)); 

DB.GetCollection<User>(Dbname).Save(user, SafeMode.True); 

Il mio modello User si presenta così:

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; } 
} 
+0

che autista stai usando? – atbebtg

risposta

8

il codice sia giusto. Ecco un programma completo corsa per mettere a confronto contro:

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 = "[email protected]" }; 
      users.Insert(john); 
      var joe = new User { FirstName = "Joe", LastName = "Smith", EmailAddress = "[email protected]" }; 
      users.Insert(joe); // should throw exception 
     } 
    } 
} 

È inoltre possibile utilizzare la shell mongo per confermare che l'indice ottenuto creato:

> 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 
     } 
] 
> 
+0

Funziona bene ma voglio due o più campi per ridurre i duplicati. Suggeriscimi –

27

L'indice univoco ha solo bisogno di essere creata una volta, dopo di ciò qualsiasi inserimento di documenti che contenga un indirizzo email duplicato avrà esito negativo. Ecco un esempio:

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

EnsureIndex() è deprecato/obsoleto per la versione C# driver mongo 2.0 spec: http://api.mongodb.org/csharp/current/html/M_MongoDB_Driver_MongoCollection_EnsureIndex_2.htm

heres come farlo asincrona e tramite il codice 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); 
Problemi correlati