Misi
Misi

Reputation: 748

Checking if a part of a text field if is contained in an array of strings

I have an array of search terms(userSearchTerms) that I want to filter in the Users collection(users = _id + name, ex: Bill Gates, Paul Allen, Satya Nadella).

userSearchTerms = string[] {"Bil", "Pau", "Saty"};

In mongodb, I managed to query like this:

db.users.find({ name: { $in: [ /Bil/i, /Pau/i, /Saty/i ] } })

But I'm not able to achieve this with the C# driver(currently using v2.4.4):

filter.Where(u => userSearchTerms.Any(st => u.Name.Contains(st)));

But I get this ex: ArgumentException: 'Unsupported filter: Any(value(System.String[]).Where({document}{Name}.Contains({document}))).'

Q: Is there any way that I can achieve this with the C# driver?

Upvotes: 1

Views: 222

Answers (1)

Neil
Neil

Reputation: 1633

You could try merging all of your search terms into a single regex and evaluating without using $in:

// Produces a regex like: (Bil|Pau|Saty)
string regex = $"^({string.Join("|", userSearchTerms)})";

var filter = new FilterDefinitionBuilder<User>()
    .Regex(u => u.Name, new BsonRegularExpression(regex, "i"));

var users = collection.Find(filter).ToEnumerable();

Upvotes: 0

Related Questions