摘要:[MongoDB][001][官方api學習紀錄]FilterDefinitionBuilder
c# driver version:2.1
內有兩個詳細的api可用:
1.
FilterDefinitionBuilder<TDocument>.Eq<TField> Method (Expression<Func<TDocument, TField>>, TField)
官方的說法是(也太簡潔了吧):
Creates an equality filter.
我的程度能理解的說法是:
第一個參數用lambda expression轉成第二個參數的物件型態(TDocument Class裡面的TField成員的型態)之後,這兩個參數去比較是否相同
舉例來說:
var filter = Builders<GridFSFileInfo>.Filter.Eq(x=>x.Id,new ObjectId(objectID));
上面的例子就是將傳進去的字串objectID轉型成ObjectID物件之後,去跟資料庫裡面的x.Id欄位作比較(此欄位的型態為ObjectId)
最後資料就撈出所有欄位值為ObjectId(objectID)的所有資料
2.
FilterDefinitionBuilder
官方的說法是(同樣是太簡潔了吧...):
Creates an equality filter.
我的程度能理解的說法是:
caller丟入的第1個字串參數(代表要比較的欄位名稱)會利用FieldDefinition<TDocument, TField>去做implicit convertion,
將字串轉成TDocument class裡面的TField物件(也就是將欄位物件化),然後再去跟第二個物件欄位值做比較
舉例來說:
var filter = Builders<GridFSFileInfo>.Filter.Eq("_id", new ObjectId(objectID));
上面的例子會把字串_id轉型成GridFSFileInfo裡面的ObjectID物件,然後再去跟目標的new ObjectId(objectID)做比較,看是否相等
最後就是找出資料庫裡欄位值為ObjectId(objectID)的資料
完整的範例程式碼如下:
string objectID = ObjectIDTxt.Text.Trim();
GridFSBucketOptions bucketOptions = new GridFSBucketOptions();
bucketOptions.BucketName = "Alliance";
ObjectId gridfsObjectID = new ObjectId(objectID);
//下面這行寫法OK,是因為字串與字串可以直接比較
//var filter = Builders.Filter.Eq(x => x.Filename, "9fdd3901-ee7d-430b-8cbe-21eff0661560.pdf");
//無法正確執行,Unable to determine the serialization information for Id,是因為物件與物件無法直接做比較
//var filter = Builders.Filter.Eq(x=>x.Id,new ObjectId(objectID));
//參考這篇文章之後
//http://stackoverflow.com/questions/33495208/mongodbfail-to-get-gridfsfileinfo-by-objectid-but-succeed-by-filename
//Paul的解答有效!這個Eq的寫法會把_id隱性轉型(術語叫implicit convertion)為ObjectID型態
var filter = Builders.Filter.Eq("_id", new ObjectId(objectID));
var findOptions = new GridFSFindOptions();
findOptions.Limit = 1;
var myBucket = new GridFSBucket(_database, bucketOptions);
//官網僅提供非同步方法範例
//這是Miguel的解答,compile會有錯
//using (var taskOfCursor = Task.Run(() => myBucket.FindAsync(x => x.Id == new MongoDB.Bson.ObjectId(objectID), findOptions)))
using (var taskOfCursor = Task.Run(() => myBucket.FindAsync(filter, findOptions)))
{
var test = taskOfCursor.Result;
var taskOfList = Task.Run(() => taskOfCursor.Result.ToListAsync());
GridFSFileInfo fileInfo = taskOfList.Result.FirstOrDefault();
if (fileInfo != null)
{
FileNameLbl.Text = fileInfo.Filename;
}
}
參考資料:
FilterDefinitionBuilder<TDocument>.Eq Method
[MongoDB][000][官方api學習紀錄]FieldDefinitionImplicit Conversion (String to FieldDefinition)
http://www.dotblogs.com.tw/kevinya/archive/2015/11/04/153794.aspx