Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

345
Views
PyMongo: regex match document field against python variable

I have a db with documents with this format:

document1:
    "source_dir": 
    [
        "D:\dir1", 
        "D:\dir2"
    ]

document2:
    "source_dir": 
    [
        "D:\dir3", 
        "D:\dir4"
    ]

And in Python I have this path variable:

path = "D:\dir1\testFile.txt"

How can I query the db using the "path" variable so the return value is the document which "source_dir" array field contains an item that matches the start of path variable content?

In this case, the return value would be document1, since its source_dir field contains D:\dir1 and path starts with D:\dir1.

Thanks.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can utilise aggregation operator $indexCP to search a string for an occurrence of a substring. The trick here is to reverse the search, using the source_dir value to search in the variable.

For example:

fullpath = "D:\\dir1\\testFile.txt"

pipeline = [
        {"$unwind": "$source_dir"},
        {"$match":{
            "$expr":{
                "$ne":[{"$indexOfCP":[fullpath, "$source_dir"]}, -1]
        }}}]
result = client.dbname.collname.aggregate(pipeline)
for doc in result:
    print(doc)

See also aggregation pipeline to find more operators

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!