Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating MongoDB Unique Key with C#

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; } } 
like image 802
Uter1007 Avatar asked Jun 02 '11 18:06

Uter1007


People also ask

How do I create a unique key in MongoDB?

To create a unique index, use the db. collection. createIndex() method with the unique option set to true .

How does MongoDB store unique data?

MongoDB's Unique Constraint makes certain that the fields indexed in it, do not store duplicate values for the same field, i.e., making sure the uniqueness of fields. By default, MongoDB enforces this unique constraint on the “_id” field, while inserting new data.

What is ensureIndex in MongoDB?

They store the value of a specific field or more than one fields (i.e. set of fields), which are ordered by the value of the field as indicated in the index. The ensureIndex () Method. In MongoDB, we use 'ensureIndex ()' method to create an index.


2 Answers

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); } 
like image 65
Chris Fulstow Avatar answered Oct 02 '22 05:10

Chris Fulstow


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<User>("EmailAddress"); var indexDefinition = new IndexKeysDefinitionBuilder<User>().Ascending(field); await db.GetCollection<Users>("users").Indexes.CreateOneAsync(indexDefinition, options); 

In case of a non-string index:

   var options = new CreateIndexOptions() { Unique = true };    IndexKeysDefinition<Foo> keyCode = "{ Code: 1 }";    var codeIndexModel = new CreateIndexModel<Foo>(keyCode, options); 
like image 32
kennydust Avatar answered Oct 02 '22 05:10

kennydust