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

[MongoDB .NET Driver] Find & FindAsync sample

More than 3 years have passed since last update.

Driver & Environment & Initialization & Mapping Class

請參考
[MongoDB .NET Driver] Indexes.CreateOneAsync sample

Single Filter

假設已知PersonId
查詢此Member資料寫法如下

var filter = Builders<Member>.Filter.Eq<string>(m => m.PersonId, id);
var member = db.GetCollection<Member>(colName).Find(filter).FirstOrDefaultAsync().Result;

Projection

同上範例
但是查詢結果只需要此Member的Phone資料寫法如下

var filter = Builders<Member>.Filter.Eq<string>(m => m.PersonId, id);
// 預設會傳回_id欄位, 所以排除掉
var projection = Builders<Member>.Projection.Exclude(m => m.Id).Include(m => m.Phone);
var doc = db.GetCollection<Member>(colName).Find(filter).Project(projection).FirstOrDefaultAsync().Result;
var phone = BsonSerializer.Deserialize<string>(doc.Values.ElementAt(0).ToJson());

Compose Filter

假設需要查詢某地區特定性別的Member們
每次批次取得5000筆
寫法如下

var builder = Builders<Member>.Filter;
var filters = new List<FilterDefinition<Member>>();

filters.Add(builder.Eq(m => m.ZipCode, zipCode));
filters.Add(builder.Eq(m => m.Gender, gender));

IAsyncCursor<Member> cursor = db.GetCollection<Member>(colName).FindAsync(builder.And(filters), new FindOptions<Member>() { BatchSize = 5000 }).Result;

List<Member> members = new List<Member>();
while (cursor.MoveNextAsync().Result)
{
    members.AddRange(cursor.Current);
}
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
ユーザーは見つかりませんでした