【问题标题】:MongoDB C# Query for 'Like' on stringMongoDB C#查询字符串上的“喜欢”
【发布时间】:2011-12-05 07:43:33
【问题描述】:

我正在使用官方的 mongodb c# 驱动程序。 我想查询类似于 SQL Like 的 mongodb c# 驱动程序中的 db.users.find({name:/Joe/} 之类的东西

【问题讨论】:

标签: c# mongodb mongodb-.net-driver mongodb-csharp-2.0


【解决方案1】:

c# 查询将如下所示:

Query.Matches("name", BsonRegularExpression.Create(new Regex("Joe")));

更新:

根据@RoberStam 的建议,有更简单的方法可以做到这一点:

Query.Matches("name", "Joe") 

【讨论】:

  • 你可以写:Query.Matches("name", "Joe")
  • 您将如何使用新的 2.0 驱动程序?
【解决方案2】:

对于c#驱动2.1(MongoDB 3.0)

var collection = database.GetCollection<BsonDocument>("<<name of the collection>>");

var filter = Builders<BsonDocument>.Filter.Regex("name", new BsonRegularExpression("Joe"));

var result = await collection.Find(filter).ToListAsync();

对于c#驱动2.2(MongoDB 3.0)

var filter = new BsonDocument { { parameterName, new BsonDocument { { "$regex", value }, { "$options", "i"} } } }

var result = collection.Find(filter).ToList();

【讨论】:

    【解决方案3】:

    MongoDB C# 驱动程序有一个您可以使用的BsonRegex type

    Regex 是最接近 SQL LIKE 语句的表达式。

    注意前缀正则表达式可以使用索引:/^Joe/ 将使用索引,/Joe/ 不会。

    【讨论】:

      【解决方案4】:

      感谢@Sridhar - 对我有用的类似方法

      public List<SearchModel> GetSearchResult(string searchParam) => _collection.Find(new BsonDocument { { "Datetime", new BsonDocument { { "$regex", searchParam }, { "$options", "i" } } } }).ToList(); // Search DateTime "Like"
      

      【讨论】:

        【解决方案5】:

        假设我需要从 Mongodb 文档的属性中搜索变量“textToSearch”的值。

        示例:我们必须在JobModel.Title 包含manager 的所有记录中搜索经理。那是记录中的textToSearch=manager。 (textToSearch 是一个字符串类型。我在答案的末尾添加了一些正则表达式。为了涵盖 textToSearch 包含的内容,textToSearch 开始于几个场景)

        等效的 C# 代码:

        Note: I have also shown how you can append to your existing filter, ignore it if not required.
        
        var mongoBuilder = Builders<BsonDocument>.Filter;
        var filter = mongoBuilder.Eq(y => y.JobModel.Category, "full time");
        
        if (!string.IsNullOrEmpty(textToSearch))
        {
            textToSearch = "/.*" + textToSearch + ".*/i"; // this regex will search all the records which contains textToSearch and ignores case
            filter = filter & mongoBuilder.Regex(y => y.JobModel.Title, new BsonRegularExpression(textToSearch));
        }                
        
        

        等效的 Mongo 查询代码:

        db.jobs.find({ "JobModel.Category" : "full time", 
        "JobModel.Title" : /.*manager.*/i })  
        

        一些有用的正则表达式:

        • 此正则表达式将搜索所有包含 textToSearch 并忽略大小写的记录。 textToSearch = "/.*" + textToSearch + ".*/i";
        • 此正则表达式将搜索所有以 textToSearch 开头并忽略大小写的记录。 textToSearch = "/^" + textToSearch + "/i";
        • 此正则表达式将搜索所有以 textToSearch 开头的记录,并且不忽略大小写。 textToSearch = "/.*" + textToSearch + ".*/";

        【讨论】:

          猜你喜欢
          • 2019-04-17
          • 2020-04-15
          • 1970-01-01
          • 2015-06-17
          • 1970-01-01
          • 2014-03-30
          • 2012-06-25
          • 2014-02-08
          • 2012-12-23
          相关资源
          最近更新 更多