Searching string with special characters in MongoDB document

后端 未结 7 1890
清歌不尽
清歌不尽 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:20

    Escape all regex special characters:

      req.query.name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    

    Create a query with regex and option "i" (ignore case):

      const databaseQuery.name = new RegExp(`${req.query.name}`, 'i');
    

    Perform a search with a query:

      db.collection.find(databaseQuery)
    

    Note: don't forget to create indexes for the fields that you will search through. Indexing fields increases the speed of your regex queries. In my case for my 'name' field it would be like this:

      db.collection.createIndex({ name: "text" })
    
    0 讨论(0)
  • 2020-12-06 00:20

    Define the search key under the re.escape function that will resolve the issue for special character regex.

    {search_field: {"$regex": '{}.*'.format(re.escape(search_key)),"$options": 'i'}}
    
    0 讨论(0)
  • 2020-12-06 00:22

    You have to escape $ by \:

    db.myCollection.find({ myKey : /.*\$aus.*/i }); 
    // OR
    db.myCollection.find({myKey: { $regex: '.*\\$aus.*', $options: 'i'}})
    
    0 讨论(0)
  • 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' });
    
    0 讨论(0)
  • 2020-12-06 00:35

    The Java Equivalent for https://stackoverflow.com/a/52322010/8208083 is as follows:

    Pattern p = Pattern.compile("[\\.\\*\\+\\?\\^\\${}\\(\\)|\\]\\[\\\\]");
    Matcher m = p.matcher(searchKeyword);
    searchKeyword = m.replaceAll("\\\\$0");
    

    This is useful when you need to pass the search keyword in the @Query annotation of Spring.

    0 讨论(0)
  • 2020-12-06 00:39
    db.test.insert({word: 'hai('});
    db.test.insert({word: 'jana'});
    

    Output be like that :

    { "_id" : ObjectId("56f27fb71d843581261433c6"), "word" : "hai(" }
    { "_id" : ObjectId("56f27ffe1d843581261433c8"), "word" : "jana" }
    

    Note : Want the special char row alone so

    db.test.find({word:{$regex:"\\("}});
    

    Output be like this:

    { "_id" : ObjectId("56f27fb71d843581261433c6"), "word" : "hai(" }
    
    0 讨论(0)
提交回复
热议问题