Advertisement
Guest User

Untitled

a guest
Feb 20th, 2016
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.78 KB | None | 0 0
  1.         /// <summary>
  2.         /// Ensures that a collections have a compound index of two fields.
  3.         /// </summary>
  4.         /// <param name="fieldName1">Field to be used as first part of the index.</param>
  5.         /// <param name="fieldName2">Field to be used as second part of the index.</param>
  6.         /// <param name="collectionName">Collection to apply this index.</param>
  7.         /// <param name="indexDirection">Index direction. 1 means ascending,
  8.         /// 0 means descending. Each bit corresponds to a field, by order.</param>
  9.         /// <param name="setUnique">If set to <c>true</c> set unique.</param>      
  10.         public void EnsureCompoundIndex (string fieldName1, string fieldName2,
  11.             string collectionName, byte indexDirection=11, bool setUnique = true)
  12.         {
  13.             var collection = _database.GetCollection<BsonDocument>(collectionName);
  14.             IndexKeysDefinition<BsonDocument> keys;
  15.             CreateIndexOptions options = new CreateIndexOptions();
  16.  
  17.             // Set keys
  18.             switch (indexDirection)
  19.             {
  20.                 case 00:
  21.                     keys = Builders<BsonDocument>.IndexKeys
  22.                     .Descending (fieldName1)
  23.                     .Descending (fieldName2);
  24.                     break;
  25.                 case 01:
  26.                     keys = Builders<BsonDocument>.IndexKeys
  27.                     .Descending (fieldName1)
  28.                     .Ascending  (fieldName2);
  29.                     break;
  30.                 case 10:
  31.                     keys = Builders<BsonDocument>.IndexKeys
  32.                     .Ascending  (fieldName1)
  33.                     .Descending (fieldName2);
  34.                     break;
  35.                 case 11:
  36.                     keys = Builders<BsonDocument>.IndexKeys
  37.                     .Ascending (fieldName1)
  38.                     .Ascending (fieldName2);
  39.                     break;
  40.                 default:
  41.                     throw new Exception ("indexDirection must have a value " +
  42.                         "between 00 and 11 for this overload.");
  43.             }
  44.  
  45.             // Set options
  46.             if   (setUnique) options.Unique = true;
  47.             else             options.Unique = false;
  48.  
  49.             // Create index
  50.             collection.Indexes.CreateOne(keys, options);
  51.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement