MongoDB: Is it possible to make a case-insensitive

2018-12-31 09:12发布

Example:

> db.stuff.save({"foo":"bar"});

> db.stuff.find({"foo":"bar"}).count();
1
> db.stuff.find({"foo":"BAR"}).count();
0

23条回答
长期被迫恋爱
2楼-- · 2018-12-31 09:38

Suppose you want to search "column" in "Table" and you want case insenstive search. The best and efficient way is as below;

//create empty JSON Object
mycolumn = {};

//check if column has valid value
if(column) {
    mycolumn.column = {$regex: new RegExp(column), $options: "i"};
}
Table.find(mycolumn);

Above code just adds your search value as RegEx and searches in with insensitve criteria set with "i" as option.

All the best.

查看更多
若你有天会懂
3楼-- · 2018-12-31 09:40

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 .

查看更多
有味是清欢
4楼-- · 2018-12-31 09:41

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.

查看更多
其实,你不懂
5楼-- · 2018-12-31 09:44

These have been tested for string searches

{'_id': /.*CM.*/}               ||find _id where _id contains   ->CM
{'_id': /^CM/}                  ||find _id where _id starts     ->CM
{'_id': /CM$/}                  ||find _id where _id ends       ->CM

{'_id': /.*UcM075237.*/i}       ||find _id where _id contains   ->UcM075237, ignore upper/lower case
{'_id': /^UcM075237/i}          ||find _id where _id starts     ->UcM075237, ignore upper/lower case
{'_id': /UcM075237$/i}          ||find _id where _id ends       ->UcM075237, ignore upper/lower case
查看更多
素衣白纱
6楼-- · 2018-12-31 09:45

Mongo (current version 2.0.0) doesn't allow case-insensitive searches against indexed fields - see their documentation. For non-indexed fields, the regexes listed in the other answers should be fine.

查看更多
临风纵饮
7楼-- · 2018-12-31 09:45

As you can see in mongo docs - since version 3.2 $text index is case-insensitive by default: https://docs.mongodb.com/manual/core/index-text/#text-index-case-insensitivity

Create a text index and use $text operator in your query.

查看更多
登录 后发表回答