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

后端 未结 24 2183
谎友^
谎友^ 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:35

    You can use Case Insensitive Indexes:

    The following example creates a collection with no default collation, then adds an index on the name field with a case insensitive collation. International Components for Unicode

    /* strength: CollationStrength.Secondary
    * Secondary level of comparison. Collation performs comparisons up to secondary * differences, such as diacritics. That is, collation performs comparisons of 
    * base characters (primary differences) and diacritics (secondary differences). * Differences between base characters takes precedence over secondary 
    * differences.
    */
    db.users.createIndex( { name: 1 }, collation: { locale: 'tr', strength: 2 } } )
    

    To use the index, queries must specify the same collation.

    db.users.insert( [ { name: "Oğuz" },
                                { name: "oğuz" },
                                { name: "OĞUZ" } ] )
    
    // does not use index, finds one result
    db.users.find( { name: "oğuz" } )
    
    // uses the index, finds three results
    db.users.find( { name: "oğuz" } ).collation( { locale: 'tr', strength: 2 } )
    
    // does not use the index, finds three results (different strength)
    db.users.find( { name: "oğuz" } ).collation( { locale: 'tr', strength: 1 } )
    

    or you can create a collection with default collation:

    db.createCollection("users", { collation: { locale: 'tr', strength: 2 } } )
    db.users.createIndex( { name : 1 } ) // inherits the default collation
    

提交回复
热议问题