MongoDB C#查询字符串上的"Like"

gsa*_*wal 24 mongodb mongodb-.net-driver

我正在使用官方的mongodb c#驱动程序.我想查询mongodb simliar到SQL就像db.users.find({name:/Joe/}在c#driver中一样

And*_*ich 42

c#查询将如下所示:

Query.Matches("name", BsonRegularExpression.Create(new Regex("Joe")));
Run Code Online (Sandbox Code Playgroud)

更新:

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

Query.Matches("name", "Joe") 
Run Code Online (Sandbox Code Playgroud)

  • 你会如何使用新的2.0驱动程序? (5认同)
  • 你可以写:Query.Matches("name","Joe") (4认同)

Sri*_*har 27

对于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();
Run Code Online (Sandbox Code Playgroud)

对于c#驱动程序2.2(MongoDB 3.0)

var filter = new BsonDocument { { parameterName, new BsonDocument { { "$regex", value }, { "$options", "i"} } } }

var result = collection.Find(filter).ToList();
Run Code Online (Sandbox Code Playgroud)


Gat*_* VP 10

MongoDB C#驱动程序具有您可以使用的BsonRegex类型.

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

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