Home > Back-end >  StartsWith & Contains with looslely typed mongodb data
StartsWith & Contains with looslely typed mongodb data

Time:10-17

I can use the following for exact match 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 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 error:

Method 'Boolean Contains(System.String)' declared on type 'System.String' cannot be called with instance of type 'MongoDB.Bson.BsonValue'

How do I use these filters?

CodePudding user response:

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

CodePudding user response:

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);
  • Related