1. 程式人生 > 其它 >c# Mongo.Driver實現多欄位模糊查詢 or like

c# Mongo.Driver實現多欄位模糊查詢 or like

我們專案中使用mongodb作為資料庫來實現地理座標距離計算,我是通過aggregation pipeline(聚合管道)建立查詢的。

產品需求:根據名稱模糊過濾(單個欄位)

var client = new MongoClient("mongodb://127.0.0.1:27017");
            var db = client.GetDatabase("xxxLocations");
            var places = db.GetCollection<Places>("Places");

var queryCondition = new BsonDocument
            {
                {
"IsDeleted",0 } }; string keyword = "哈哈"; queryCondition.Add("Name", new BsonRegularExpression($"/{keyword}/")); var match = new BsonDocument { {"$match",queryCondition } }; searchConditions.Add(match);
var list = places.Aggregate(PipelineDefinition<Places, Places>.Create(searchConditions)).ToList();

功能弄出來後,經過測試後,我屁顛屁顛的衝了杯咖啡,準備好上生產,然後市場姐姐就過來告訴我,這個模糊搜尋要可以多個欄位,我的內心是拒絕的,但...人家是“衣食父母”,嗯,然後就有了多個欄位的版本。

產品需求:根據多個欄位模糊過濾

var client = new MongoClient("mongodb://127.0.0.1:27017");
            var db = client.GetDatabase("
xxxLocations"); var places = db.GetCollection<Places>("Places"); var queryCondition = new BsonDocument { {"IsDeleted",0 } }; string keyword = "哈哈"; //queryCondition.Add("Name", new BsonRegularExpression($"/{keyword}/")); //手動高亮 var orLikeArray = new BsonArray { { new BsonDocument { {"Name",new BsonRegularExpression($"/{keyword}/") } } }, { new BsonDocument { {"NickName",new BsonRegularExpression($"/{keyword}/") } } } }; var bsonOr = new BsonDocument { { "$or",orLikeArray } }; queryCondition.AddRange(bsonOr); //手動高亮結束 var match = new BsonDocument { {"$match",queryCondition } }; searchConditions.Add(match); var list = places.Aggregate(PipelineDefinition<Places, Places>.Create(searchConditions)).ToList();

目前還沒有研究透mongodb.driver,還有很多東西等我去探索,這裡只是demo記錄一下mongodb多欄位模糊搜尋的一個方式。