The escaping problem of "Python" Pymongo query

Source: Internet
Author: User

A regular query was used when querying MONGO

Set string to str = '/ab/cd.ef?g= '

There is no match directly with the regular query.

Collection.find ({"re": {'$regex': str},' b': {'  $nin': [False]}}). Count ()

The reason is/. ? are special characters in regular expressions and need to be escaped with "\" If you want to preserve the original meaning.

Change the string to str = ' \/ab\/cd\.ef\?g= '

However, since "\" is a special symbol in Python, use "\ \" to represent

Define a function of character escapes

deftransfer_str (str): New_str=""Special= ['/','^','$','*','+','?','.']     forCinchStr:ifCinchSpecial:new_str+='\\'New_str+=CreturnNew_str

and then call

Collection.find ({"re": {'$regex': Transfer_str (str)}, ' b ': {'$nin': [False]}}). Count ()

So we can get the right results.

"Python" Pymongo the Escape problem when querying

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.