我們項目中使用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多字段模糊搜索的一個方式。