How do I make case-insensitive queries on Mongodb?

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

    MongoDB 3.4 now includes the ability to make a true case-insensitive index, which will dramtically increase the speed of case insensitive lookups on large datasets. It is made by specifying a collation with a strength of 2.

    Probably the easiest way to do it is to set a collation on the database. Then all queries inherit that collation and will use it:

    db.createCollection("cities", { collation: { locale: 'en_US', strength: 2 } } )
    db.names.createIndex( { city: 1 } ) // inherits the default collation
    

    You can also do it like this:

    db.myCollection.createIndex({city: 1}, {collation: {locale: "en", strength: 2}});
    

    And use it like this:

    db.myCollection.find({city: "new york"}).collation({locale: "en", strength: 2});
    

    This will return cities named "new york", "New York", "New york", etc.

    For more info: https://jira.mongodb.org/browse/SERVER-90

提交回复
热议问题