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

问题描述 投票:24回答:3

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

mongodb mongodb-.net-driver
3个回答
41
投票

c#查询将如下所示:

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

更新:

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

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

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

10
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.