3

I have been working out for a case-insensitive search for hours and I still can`t find a solution...

I have data stored in MongoDB and formatted like this :

{
  id: 12345,
  name: "foo",
  area: ["US","California"],
  ...
}

And I wanna use query to find results, as a list, that area partially matches the area string. For example, if I want to find people who are in us, with lower case. My method looks like this:

public async Task<IEnumerable<Restaurant>> GetByArea(string area)
{
     var result = await _context.Users
          .Find(user => user.Area.Contains(area))
          .ToListAsync();

     try
     {
          return result;
     }
     catch (Exception e)
     {
          return null;
     }
}

How should I modify my code to conform case-insensitive search? The IEqualityComparer's methods won't be translated to MongoDB query.

1
  • I'd look into MongoDB collation Commented Jan 9, 2020 at 8:27

2 Answers 2

2

I'm not sure it would work, but you can try to use the method Any:

var result = await _context.Users
    .Find(user => user.Area.Any(item => item.ToLower() == area.ToLower()))
    .ToListAsync();
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! that actually works! I was stuck on how to use StringComparer and not looked back the simple way!!
0

Would something like this help?

(user => user.Area.Contains(area, StringComparer.InvariantCultureIgnoreCase))

1 Comment

I tried, and I think some of the methods are not supported in fluent API? I got not supported exception.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.