Performing regex Queries with pymongo

Performing regex Queries with pymongo

Asked on January 5, 2019 in MongoDB.
Add Comment


  • 3 Answer(s)

    Just you want to try this one,  If you want to include regular expression options (such as ignore case)

    import re
    regx = re.compile("^foo", re.IGNORECASE)
    db.users.find_one({"files": regx})
    
    Answered on January 5, 2019.
    Add Comment

    For the regex is changed pymongo is work done in different but is just as easy:

    The following code as work like regex

    db.collectionname.find({'files':{'$regex':'^File'}})
    
    

    This following document will match like a document that have a files property that has a item within that starts with File

    Answered on January 5, 2019.
    Add Comment

    To ignore the duplicate compilation you can use the bson regex wrapper that comes with PyMongo

    >>> regx = bson.regex.Regex('^foo')
    
    >>> db.users.find_one({"files": regx})
    
    

    The string is stored in the regex so find_one can then detect the argument as a ‘Regex’ type and form the appropriate Mongo query.

    In Python answer should be a most valuable answer in other answer

    >>> db.collectionname.find({'files':{'$regex':'^File'}})
    
    

    if you plan to use regex queries because there are some caveats. It’s worth reading up on the bson Regex documentation

    Answered on January 5, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.