Search code examples
c#mongodblambdamongodb-.net-driver

How to perform a full text search in MongoDb with C# Lambda expression


There are a lot of answers how to get full-text search using Mongodb Driver Builders. But it has another way of ORM is lambdaexpressions to filter query.

var collection = _mongoContextFactory.GetCollection<Foo>();
collection.FindSync(x => x.Created >= new DateTime());

So How I will can to get full-text search using lambda ( I use specification pattern that provides expression interface)


Solution

  • Ok, I tried to find solution inside ExpressionFilterDefinition (MongodbDriver converts lambda expression to this filter) and was defeated.

    So, directly full text search is not supported by lambda expression. I switched on my imagination and created workaround for this task. I made abstract class for dto entity that utilize Full-Text index

      public abstract class FullTextSearchEntity
        {
            [BsonElement("$text"), BsonIgnoreIfNull]
            public FullTextSearchOption FullTextSearch { get; set; }
        }
    

    As You can guess FullTextSearchOption repeats BSON structure for utilize fulltext index

      public class FullTextSearchOption
        {
            [BsonElement("$search"), BsonIgnoreIfNull]
            private string Search { get; set; }
    
            public FullTextSearchOption(string search)
            {
                Search = search;
            }
        }
    

    And finally I added specification for usage this workaround:

      public class FullTextSearchSpecification<T> : SpecificationBase<T> where T: FullTextSearchEntity
        {
            private readonly string _searchQuery;
    
            public FullTextSearchSpecification(string searchQuery)
            {
                _searchQuery= searchQuery;
            }
    
            public override Expression<Func<T, bool>> ToExpression()
            {
                return entity=> entity.FullTextSearch == new FullTextSearchOption(_searchQuery);
            }
        }
    

    Bingo!