Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

348
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda