Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

347
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda