Performing regex Queries with pymongo

RC1140 picture RC1140 · Aug 14, 2010 · Viewed 69.4k times · Source

I am trying to perform a regex query using pymongo against a mongodb server. The document structure is as follows

{
  "files": [
    "File 1",
    "File 2",
    "File 3",
    "File 4"
  ],
  "rootFolder": "/Location/Of/Files"
}

I want to get all the files that match the pattern *File. I tried doing this as such

db.collectionName.find({'files':'/^File/'})

Yet i get nothing back , am i missing something because according to the mongodb docs this should be possible. If I perform the query in the mongo console it works fine , does this mean the api doesnt support it or am I just using it incorrectly

Answer

Eric picture Eric · Feb 2, 2011

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

import re
regx = re.compile("^foo", re.IGNORECASE)
db.users.find_one({"files": regx})