简体   繁体   中英

C# MongoDB check if array contains strings case insensitive

I'm new to MongoDB and I'm trying to check if an input array of strings has any values that matches with a nested array of strings on any document.

public IEnumerable<Cocktail> FindByIngredients(List<string> inputIngredients)
    {
        inputIngredients = inputIngredients.ConvertAll(ingredient => ingredient.ToLower());
        var filter = Builders<Cocktail>.Filter
            .AnyIn(x => x.IngredientList, inputIngredients);

        var cocktails = _collection.Find(filter).ToList();
       
        return cocktails;
    }

Currently, I got above, but it's not case insensitive, how would I go about making this case insensitive?

JSON document from collection

You can specify the collation when executing the query and by that change the way that MongoDB handles strings. See this [link][1] for details.

For instance, if you want to use English-US as locale for querying, you can use the following code:

public IEnumerable<Cocktail> FindByIngredients(List<string> inputIngredients)
{
    inputIngredients = inputIngredients.ConvertAll(ingredient => ingredient.ToLower());
    var filter = Builders<Cocktail>.Filter
        .AnyIn(x => x.IngredientList, inputIngredients);

    var options = new FindOptions() 
    {
      Collation = new Collation("en_US")
    };
    var cocktails = _collection.Find(filter, options).ToList();
   
    return cocktails;
}

If you do not specify a collation, a simple binary comparison is used, hence the distinction between upper und lower case.

If you want to support the query with an index, keep in mind that the index must also use the same collation that is used when querying. [1]: https://www.mongodb.com/docs/manual/reference/collation/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM