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

1
  • 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. Commented Nov 17, 2021 at 14:32

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.