Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net Core query case-insensitive string data in list from MongoDb [duplicate]

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.

like image 322
Liu Junhan Avatar asked Feb 16 '26 17:02

Liu Junhan


1 Answers

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();
like image 167
smolchanovsky Avatar answered Feb 18 '26 06:02

smolchanovsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!