MongoDB C# 查询“Like”串上
我正在使用官方 mongodb C# 驱动程序。 我想查询类似于 SQL 的 mongodb C# 驱动程序中类似于 db.users.find({name:/Joe/}
i am using official mongodb c# driver.
i want to query mongodb simliar to SQL Like
something like db.users.find({name:/Joe/}
in c# driver
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
c# 查询将如下所示:
更新:
根据 @RoberStam 建议,有更简单的方法可以执行此操作:
c# query will looks like:
Update:
As per @RoberStam suggestion, there is more simple way to do this:
对于 c# 驱动程序 2.1 (MongoDB 3.0)
对于 c# 驱动程序 2.2 (MongoDB 3.0)
For the c# driver 2.1 (MongoDB 3.0)
For the c# driver 2.2 (MongoDB 3.0)
MongoDB C# 驱动程序有一个可以使用的 BsonRegex 类型 。
正则表达式是最接近 SQL
LIKE
语句的。请注意,带前缀的正则表达式可以使用索引:
/^Joe/
将使用索引,/Joe/
不会。MongoDB C# driver has a BsonRegex type that you can use.
Regex is the closest you will get to the SQL
LIKE
statement.Note that prefixed Regexes can use indexes:
/^Joe/
will use an index,/Joe/
will not.假设我需要从 Mongodb 文档的属性中搜索变量“textToSearch”的值。
示例:我们必须在
JobModel.Title
包含manager
的所有记录中搜索manager。这是记录中的textToSearch=manager
。 (textToSearch
是一个字符串类型。我在答案末尾添加了一些正则表达式。为了涵盖 textToSearch 包含、textToSearch 开头以及更多场景)等效 C# 代码:
等效的 Mongo 查询代码:
一些有用的正则表达式:
textToSearch = "/.*" + textToSearch + ".*/i";
textToSearch = "/^" + textToSearch + "/i";
textToSearch = "/.*" + textToSearch + ".*/";
Suppose I need to search the value of variable 'textToSearch' from a property of Mongodb documents.
Example: We have to search manager in all the records where
JobModel.Title
containsmanager
. That istextToSearch=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:
Equivalent Mongo Query Code:
Some Useful Regex:
textToSearch = "/.*" + textToSearch + ".*/i";
textToSearch = "/^" + textToSearch + "/i";
textToSearch = "/.*" + textToSearch + ".*/";
感谢@Sridhar - 类似的方法对我有用
Thanks to @Sridhar - similar aproach that worked for me