MongoDB: Is it possible to make a case-insensitive query?

后端 未结 24 1825
谎友^
谎友^ 2020-11-22 04:44

Example:

> db.stuff.save({\"foo\":\"bar\"});

> db.stuff.find({\"foo\":\"bar\"}).count();
1
> db.stuff.find({\"foo\":\"BAR\"}).count();
0

24条回答
  •  囚心锁ツ
    2020-11-22 05:16

    Using a filter works for me in C#.

    string s = "searchTerm";
        var filter = Builders.Filter.Where(p => p.Title.ToLower().Contains(s.ToLower()));
                    var listSorted = collection.Find(filter).ToList();
                    var list = collection.Find(filter).ToList();
    

    It may even use the index because I believe the methods are called after the return happens but I haven't tested this out yet.

    This also avoids a problem of

    var filter = Builders.Filter.Eq(p => p.Title.ToLower(), s.ToLower());
    

    that mongodb will think p.Title.ToLower() is a property and won't map properly.

提交回复
热议问题