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

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

    For any one using Golang and wishes to have case sensitive full text search with mongodb and the mgo godoc globalsign library.

    collation := &mgo.Collation{
        Locale:   "en",
        Strength: 2, 
    }
    
    
    err := collection.Find(query).Collation(collation)
    
    0 讨论(0)
  • 2020-11-22 05:25
    db.zipcodes.find({city : "NEW YORK"}); // Case-sensitive
    db.zipcodes.find({city : /NEW york/i}); // Note the 'i' flag for case-insensitivity
    
    0 讨论(0)
  • 2020-11-22 05:25

    One very important thing to keep in mind when using a Regex based query - When you are doing this for a login system, escape every single character you are searching for, and don't forget the ^ and $ operators. Lodash has a nice function for this, should you be using it already:

    db.stuff.find({$regex: new RegExp(_.escapeRegExp(bar), $options: 'i'})
    

    Why? Imagine a user entering .* as his username. That would match all usernames, enabling a login by just guessing any user's password.

    0 讨论(0)
  • 2020-11-22 05:25

    The aggregation framework was introduced in mongodb 2.2 . You can use the string operator "$strcasecmp" to make a case-insensitive comparison between strings. It's more recommended and easier than using regex.

    Here's the official document on the aggregation command operator: https://docs.mongodb.com/manual/reference/operator/aggregation/strcasecmp/#exp._S_strcasecmp .

    0 讨论(0)
  • 2020-11-22 05:26

    You could use a regex.

    In your example that would be:

    db.stuff.find( { foo: /^bar$/i } );
    

    I must say, though, maybe you could just downcase (or upcase) the value on the way in rather than incurring the extra cost every time you find it. Obviously this wont work for people's names and such, but maybe use-cases like tags.

    0 讨论(0)
  • 2020-11-22 05:26

    I've created a simple Func for the case insensitive regex, which I use in my filter.

    private Func<string, BsonRegularExpression> CaseInsensitiveCompare = (field) => 
                BsonRegularExpression.Create(new Regex(field, RegexOptions.IgnoreCase));
    

    Then you simply filter on a field as follows.

    db.stuff.find({"foo": CaseInsensitiveCompare("bar")}).count();
    
    0 讨论(0)
提交回复
热议问题