Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// <summary>
- /// Ensures that a collections have a compound index of two fields.
- /// </summary>
- /// <param name="fieldName1">Field to be used as first part of the index.</param>
- /// <param name="fieldName2">Field to be used as second part of the index.</param>
- /// <param name="collectionName">Collection to apply this index.</param>
- /// <param name="indexDirection">Index direction. 1 means ascending,
- /// 0 means descending. Each bit corresponds to a field, by order.</param>
- /// <param name="setUnique">If set to <c>true</c> set unique.</param>
- public void EnsureCompoundIndex (string fieldName1, string fieldName2,
- string collectionName, byte indexDirection=11, bool setUnique = true)
- {
- var collection = _database.GetCollection<BsonDocument>(collectionName);
- IndexKeysDefinition<BsonDocument> keys;
- CreateIndexOptions options = new CreateIndexOptions();
- // Set keys
- switch (indexDirection)
- {
- case 00:
- keys = Builders<BsonDocument>.IndexKeys
- .Descending (fieldName1)
- .Descending (fieldName2);
- break;
- case 01:
- keys = Builders<BsonDocument>.IndexKeys
- .Descending (fieldName1)
- .Ascending (fieldName2);
- break;
- case 10:
- keys = Builders<BsonDocument>.IndexKeys
- .Ascending (fieldName1)
- .Descending (fieldName2);
- break;
- case 11:
- keys = Builders<BsonDocument>.IndexKeys
- .Ascending (fieldName1)
- .Ascending (fieldName2);
- break;
- default:
- throw new Exception ("indexDirection must have a value " +
- "between 00 and 11 for this overload.");
- }
- // Set options
- if (setUnique) options.Unique = true;
- else options.Unique = false;
- // Create index
- collection.Indexes.CreateOne(keys, options);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement