1
1

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] Find & FindAsync sample

Posted at

##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);
}
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?