1

With the following model

public class Product{
    [BsonId][BsonRepresentation{BsonType.ObjectId}]
    public string Id {get; set;}
    public string ItemName {get; set;}
}

I want to write the following query:

var items = Db.Products.Find(x => SearchText.Contains(x.ItemName)).ToList();

But mongodDB gives me an error saying the query is invalid and that I can't do String.Contains(x.Field)

So how can I check if a field is contained within a string using MongoDB.Driver library

YaRmgl
  • 356
  • 1
  • 6
  • 19
  • 1
    First of all, this kills the performance. The database engine now has to load all your records and do a partial match. Fulltext search exists for a reason; build an index on index time, do not scan at runtime. You can [do a regex search though](https://stackoverflow.com/questions/8382307/mongodb-c-sharp-query-for-like-on-string). – CodeCaster Nov 17 '21 at 14:32

1 Answers1

1

An easy way to do this is with regular expressions. You can try

var filterFirstName = Builders<Customer>.Filter.Regex("FirstName", "^" + query + ".*");

If you want the results to be combined, then after applying the 2 filters, you can do like

var finalFilter = filterFirstName & filterLastName

finalFIlter has the combined results.

athagiorgos
  • 13
  • 1
  • 4