我正在使用官方的 mongodb c# 驱动程序。我想查询类似于 SQL 的 mongodb 就像db.users.find({name:/Joe/}
在 c# 驱动程序中一样
5 回答
c# 查询将如下所示:
Query.Matches("name", BsonRegularExpression.Create(new Regex("Joe")));
更新:
根据@RoberStam 的建议,有更简单的方法可以做到这一点:
Query.Matches("name", "Joe")
对于 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();
MongoDB C# 驱动程序有一个可以使用的BsonRegex 类型。
Regex 是最接近 SQLLIKE
语句的表达式。
请注意,前缀正则表达式可以使用索引:/^Joe/
将使用索引,/Joe/
不会。
感谢@Sridhar - 对我有用的类似方法
public List<SearchModel> GetSearchResult(string searchParam) => _collection.Find(new BsonDocument { { "Datetime", new BsonDocument { { "$regex", searchParam }, { "$options", "i" } } } }).ToList(); // Search DateTime "Like"
假设我需要从 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 + ".*/";