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

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

    If you need to create the regexp from a variable, this is a much better way to do it: https://stackoverflow.com/a/10728069/309514

    You can then do something like:

    var string = "SomeStringToFind";
    var regex = new RegExp(["^", string, "$"].join(""), "i");
    // Creates a regex of: /^SomeStringToFind$/i
    db.stuff.find( { foo: regex } );
    

    This has the benefit be being more programmatic or you can get a performance boost by compiling it ahead of time if you're reusing it a lot.

提交回复
热议问题