MongoDB - Unsupported filter contains in linq. How to use contains and ToLower in linq query?

Viewed 3910

MongoDB.Driver 2.10.2

_query.Where(x => list.Contains(x.Country.ToLower())).ToList();

Unsupported filter: Contains(value(System.Collections.Generic.List`1[System.String])).

How to use contains and ToLower in linq query?

1 Answers

you can't do it with linq afaik. you need to generate the following aggregation pipeline in order to get the result you want.

db.collection.aggregate([
    {
        $match: {
            $expr: {
                $in: [{ $toLower: '$Country' }, ['canada', 'mongolia']]
            }
        }
    }
])

test program:

using MongoDB.Driver;
using MongoDB.Entities;
using MongoDB.Entities.Core;
using System.Linq;

namespace StackOverFlow
{
    public class User : Entity
    {
        public string Country { get; set; }
    }

    public static class Program
    {
        private static void Main()
        {
            new DB("test");

            new User
            {
                Country = "Mongolia"
            }.Save();

            var pipeline = new Template<User>(@"
            [
                {
                    $match: {
                        $expr: {
                            $in: [{ $toLower: '$<Country>' }, [<country_list>]]
                        }
                    }
                }
            ]"
            )
            .Path(u => u.Country)
            .Tag("country_list", "'canada', 'mongolia'");

            var result = DB.Aggregate(pipeline).ToList();
        }
    }
}

Related