How do I make case-insensitive queries on Mongodb?

后端 未结 12 1167
北恋
北恋 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:12

    To find case-insensitive literals string:

    Using regex (recommended)

    db.collection.find({
        name: {
            $regex: new RegExp('^' + name.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + '$', 'i')
        }
    });
    

    Using lower-case index (faster)

    db.collection.find({
        name_lower: name.toLowerCase()
    });
    

    Regular expressions are slower than literal string matching. However, an additional lowercase field will increase your code complexity. When in doubt, use regular expressions. I would suggest to only use an explicitly lower-case field if it can replace your field, that is, you don't care about the case in the first place.

    Note that you will need to escape the name prior to regex. If you want user-input wildcards, prefer appending .replace(/%/g, '.*') after escaping so that you can match "a%" to find all names starting with 'a'.

提交回复
热议问题