How do I make case-insensitive queries on Mongodb?

后端 未结 12 1169
北恋
北恋 2020-11-27 12:02
var thename = \'Andrew\';
db.collection.find({\'name\':thename});

How do I query case insensitive? I want to find result even if \"andrew\";

12条回答
  •  抹茶落季
    2020-11-27 12:30

    Chris Fulstow's solution will work (+1), however, it may not be efficient, especially if your collection is very large. Non-rooted regular expressions (those not beginning with ^, which anchors the regular expression to the start of the string), and those using the i flag for case insensitivity will not use indexes, even if they exist.

    An alternative option you might consider is to denormalize your data to store a lower-case version of the name field, for instance as name_lower. You can then query that efficiently (especially if it is indexed) for case-insensitive exact matches like:

    db.collection.find({"name_lower": thename.toLowerCase()})
    

    Or with a prefix match (a rooted regular expression) as:

    db.collection.find( {"name_lower":
        { $regex: new RegExp("^" + thename.toLowerCase(), "i") } }
    );
    

    Both of these queries will use an index on name_lower.

提交回复
热议问题