MongoDB C#查询字符串上的“Like”

时间:2011-12-05 07:43:33

标签: mongodb mongodb-.net-driver

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

4 个答案:

答案 0 :(得分:41)

c#查询将如下所示:

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

更新

根据@RoberStam的建议,有更简单的方法:

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

答案 1 :(得分:26)

对于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();

答案 2 :(得分:10)

MongoDB C#驱动程序可以使用BsonRegex type

正则表达式是您最接近SQL LIKE语句的地方。

请注意,带前缀的Regex可以使用索引:/^Joe/将使用索引,/Joe/则不会。

答案 3 :(得分:0)

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

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