27

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

4

5 回答 5

45

c# 查询将如下所示:

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

更新:

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

Query.Matches("name", "Joe") 
于 2011-12-05T08:58:31.830 回答
34

对于 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();
于 2015-12-02T02:35:17.947 回答
10

MongoDB C# 驱动程序有一个可以使用的BsonRegex 类型。

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

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

于 2011-12-05T08:40:02.597 回答
0

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

public List<SearchModel> GetSearchResult(string searchParam) => _collection.Find(new BsonDocument { { "Datetime", new BsonDocument { { "$regex", searchParam }, { "$options", "i" } } } }).ToList(); // Search DateTime "Like"
于 2021-05-31T15:34:59.517 回答
0

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

Example: We have to search manager in all the records where JobModel.Title contains manager. That is textToSearch=manager from the records. ( textToSearch is a string type. I have added some Regexs at the end of my answer. To cover textToSearch contains, textToSearch starts with and few more scenarios)

Equivalent C# Code:

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));
}                

Equivalent Mongo Query Code:

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

Some Useful Regex:

  • this regex will search all the records which contains textToSearch and ignores case. textToSearch = "/.*" + textToSearch + ".*/i";
  • this regex will search all the records which starts with textToSearch and ignores case. textToSearch = "/^" + textToSearch + "/i";
  • this regex will search all the records which starts with textToSearch and do not ignores case. textToSearch = "/.*" + textToSearch + ".*/";
于 2021-08-30T09:23:53.563 回答