0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[MongoDB .NET Driver] Indexes.CreateOneAsync sample

Posted at

##2.0 .NET Driver
the driver is 100% async down to the lowest level
根據官網說明
底層100%實作async的方法

##Environment Version

  • .NET 4.5

  • MongoDB 3.0

##Initialization

var client = new MongoClient(connectionString);
var db = client.GetDatabase(databaseName);

##Mapping Class
假設Collection是用來儲存會員資料
Mapping Class設計如下

public class Member 
{
    public ObjectId Id { get; set; }

    public string PersonId { get; set; }

    public string Name { get; set; }

    public int Gender { get; set; }

    public string Phone { get; set; }

    public int ZipCode { get; set; }

    public string Address { get; set; }
}

##Single Index
假設查詢PersonId次數很頻繁
則可以對PersonId建立升冪1的index

var singleIndex = await db.GetCollection<Member>(colName).Indexes.CreateOneAsync(Builders<Member>.IndexKeys.Ascending(_ => _.PersonId)).ConfigureAwait(continueOnCapturedContext: false);

##Combine Index
假設需要查詢某地區特定性別的會員
則可以對Gender及ZipCode建立升冪1的複合index

var combineIndex = await db.GetCollection<Member>(colName).Indexes.CreateOneAsync(Builders<TaMember>.IndexKeys.Combine(
    Builders<Member>.IndexKeys.Ascending(_ => _.Gender),
    Builders<Member>.IndexKeys.Ascending(_ => _.ZipCode))).ConfigureAwait(continueOnCapturedContext: false);
  1. 降冪則改寫為IndexKeys.Descending即可 2

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?