Searching string with special characters in MongoDB document

后端 未结 7 1929
清歌不尽
清歌不尽 2020-12-05 23:57

I want to search values having special characters such as \" $ / . @ > \" in a document.

Lets consider, I\'ve myKey with values like \"test$aus

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-06 00:28

    You can use https://www.npmjs.com/package/regex-escape. It is a good library for escaping special characters to be used in regular expressions

        var RegexEscape = require("regex-escape");
    
        let keyword = RegexEscape("{#/}");
        // => \{#\/\}
    
    
       db.myCollection.find({ myKey : { '$regex' : keyword, '$options' : 'mi' });
    

提交回复
热议问题