'MongoDB .NET Driver - StartsWith & Contains with loosely typed data
I can use the following for exact matches on loosely typed data in MongoDB:
var mongoClient = new MongoClient(con);
IMongoDatabase mongoDatabase = mongoClient.GetDatabase("mydb");
var profile = mongoDatabase.GetCollection<BsonDocument>("profiles");
var query = profile.AsQueryable();
var results = query.Where(x => x["first_name"] == "john").Take(10);
But how do I use the same approach to do StartsWith
and Contains
?
I tried:
var results = query.Where(x => x["first_name"].AsString.Contains("john")).Take(10);
But I get the error:
Method 'Boolean Contains(System.String)' declared on type 'System.String' cannot be called with an instance of type 'MongoDB.Bson.BsonValue'
How do I use these filters?
Solution 1:[1]
If you cast to string instead of using AsString
, it should work:
var results = query.Where(x => ((string) x["first_name"]).Contains("john")).Take(10);
Solution 2:[2]
MongoDB .NET Driver provides LinqExtensions.Inject that you can inject FilterDefinition
into a LINQ where clause.
Start with Filter
using MongoDB.Driver.Linq;
var filter = Builders<BsonDocument>
.Filter
.Regex("first_name", "^" + "john" + ".*");
var results = query.Where(x => filter.Inject())
.Take(10);
Contains Filter
using MongoDB.Driver.Linq;
var filter = Builders<BsonDocument>
.Filter
.Regex("first_name", "john");
var results = query.Where(x => filter.Inject())
.Take(10);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Brian Berns |
Solution 2 |