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

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

    For searching a variable and escaping it:

    const escapeStringRegexp = require('escape-string-regexp')
    const name = 'foo'
    db.stuff.find({name: new RegExp('^' + escapeStringRegexp(name) + '$', 'i')})   
    

    Escaping the variable protects the query against attacks with '.*' or other regex.

    escape-string-regexp

提交回复
热议问题