MongoDB C# 查询字符串上的“喜欢”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8382307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MongoDB C# Query for 'Like' on string
提问by gsagrawal
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
我正在使用官方 mongodb c# 驱动程序。我想查询类似于 SQL 的 mongodb,就像db.users.find({name:/Joe/}
在 c# 驱动程序中一样
回答by Andrew Orsich
c# query will looks like:
c# 查询将如下所示:
Query.Matches("name", BsonRegularExpression.Create(new Regex("Joe")));
Update:
更新:
As per @RoberStam suggestion, there is more simple way to do this:
根据@RoberStam 的建议,有更简单的方法可以做到这一点:
Query.Matches("name", "Joe")
回答by Sridhar
For the c# driver 2.1 (MongoDB 3.0)
对于 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();
For the c# driver 2.2 (MongoDB 3.0)
对于 c# 驱动程序 2.2 (MongoDB 3.0)
var filter = new BsonDocument { { parameterName, new BsonDocument { { "$regex", value }, { "$options", "i"} } } }
var result = collection.Find(filter).ToList();
回答by Gates VP
MongoDB C# driver has a BsonRegex typethat you can use.
MongoDB C# 驱动程序具有您可以使用的BsonRegex 类型。
Regex is the closest you will get to the SQL LIKE
statement.
正则表达式是最接近 SQLLIKE
语句的地方。
Note that prefixed Regexes can use indexes: /^Joe/
will use an index, /Joe/
will not.
请注意,带前缀的正则表达式可以使用索引:/^Joe/
将使用索引,/Joe/
不会。