search

Home  >  Q&A  >  body text

pymongo - MongoDB用正则查询时如何转义查询条件中的字符?

keyword = ''
post = collection.find({ 'key': '/^' + keyword })

如上面的代码所示,当keyword包含一些正则符号,比如$之类时,查询结果就不准确了。
不知道mongodb有没有内置转义的方法,还是说必须要外部对keyword进行转义?

伊谢尔伦伊谢尔伦2873 days ago698

reply all(1)I'll reply

  • 高洛峰

    高洛峰2017-04-21 11:18:36

    Mongodb’s regular expression query has two formats
    One is {key:{$regex:".*"}}
    The other is {key:/.*/}
    For the first escape use \
    The second use

    reply
    0
  • Cancelreply