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多字段模糊搜索的一個方式。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM