Help us understand the problem. What is going on with this article?

[MongoDB .NET Driver] Indexes.CreateOneAsync sample

More than 3 years have passed since last update.

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即可 

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした