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

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

    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.

提交回复
热议问题