2020年11月6日 星期五

MongoDB 06.C# Filter

查詢時基本上都會需要過濾條件
目前大概會使用到的如下
var builders = Builders.Filter;//建立查詢 
var filter = builders.Eq("age", 20);//過濾條件
var query = collection.Find(filter).ToList();//抓資料
條件如下
Eq等於
Ne不等於
Gt大於
Gte大於等於
Lt小於
Lte小於等於
Regex Like
In 存在裡面的
Nin 不存在裡面的
但通常條件不會這麼簡單
情境1.找年齡20~30歲
var filter = builders.Gte("age",20)  & builders.Lte("age", 30);
情境2.找年齡20~30歲或年齡50~60歲
var filter = builders.Gte("age",20)  & builders.Lte("age", 30);
filter = filter | builders.Gte("age", 50) & builders.Lte("age", 60);
情境3.找年齡20~30歲或年齡50~60歲且名字有林的
var filter = builders.Gte("age",20)  & builders.Lte("age", 30);
filter = filter | builders.Gte("age", 50) & builders.Lte("age", 60);
filter = filter & builders.Regex("Name", "林");
情境4.找年齡50、60、70歲
int[] agelist = new[] { 50, 60, 70 };
var filter = builders.In(x => x.age, agelist);
參考網站
Mongo C# driver - Building filter dynamically with nesting MongoDB C# Driver - Fastest way to perform an “IN” query on _id