Python / MongoDB - Problem with query including "OR" & "LIKE"

1

I have the following code that according to user information of a HTML form looks for a record in the MongoDB database:

# -*- coding: utf-8 -*-
import json
from pymongo import MongoClient
Conector = MongoClient('localhost:27017')

Usuario_dato = REQUEST
dato = str(Usuario_dato['find'])

print dato

Datos = Conector['CRUD']
Tabla = Datos['usuarios']


Consulta = Tabla.find({
    "$or":[
        {
            "idUsuario": '/'+dato+'/' #también he intentado { "$regex": /dato/ >>> Falla, '/dato/' >>> también falla }
        },
        {
            "nombreUsuario":'/'+dato+'/'
        },
        {
            "emailUsuario":'/'+dato+'/'
        },
        {
            "telefonoUsuario":'/'+dato+'/'
        },
        {
            "edadUsuario":'/'+dato+'/'
        }
    ]
})

Recopilado = []

for e in Consulta:
    Pre_Recopilado = {}
    for x in e:
        Pre_Recopilado[str(x)] = str(e[x])
    Recopilado.append(Pre_Recopilado)
print json.dumps(Recopilado) 

User information arrives at User_data through REQUEST

A data I assign the value that interests me to the form sent, in this case it is find :

<input type="text" name="find">

In Data and Table the connection to the CRUD database and the users

Query contains the query to be made, and this is what fails.

In the database I have:

/* 1 */
{
    "_id" : ObjectId("59b9a5837a264d076dd40a12"),
    "idUsuario" : "1093796198",
    "nombreUsuario" : "Mart&iacute;n Berm&uacute;dez",
    "emailUsuario" : "[email protected]",
    "telefonoUsuario" : "3002500989",
    "edadUsuario" : "19"
}

/* 2 */
{
    "_id" : ObjectId("59ba96d47a264d076dd43177"),
    "idUsuario" : "2135130062312",
    "nombreUsuario" : "Sofia Gonzales",
    "emailUsuario" : "[email protected]",
    "telefonoUsuario" : "3205623215",
    "edadUsuario" : "26"
}

The situation:

  • I search in the database eg: a document number of some user that may or may not exist in the records. Then I digit only 1093 and send the information.
  • I must search for that 1093 in all the fields or fields that I have defined for their respective search, in this case UserID , UserName , emailUser , telefonoUser and finally edadUsuario .
  • To perform the query, there should be a " OR " and then a " LIKE " for each field which indicates that you search for the records that contain
  • asked by Máxima Alekz 14.09.2017 в 16:52
    source

    1 answer

    0

    I found the answer:

    You must import re, so we can tell Python to treat the variable as Regular Expression.

    import re. #Importar "libreria" de Expresiones Regulares
    regex = re.compile(r'.*(%s).*'%dato) #Aqui se llama la funcion compile(), dentro de ella, se escribe r'' y dentro de las comillas puedes agregar variables como si se tratara de formato en **print**, por eso el %. 
    
    # Éste RegEx es para buscar variables que contengan el valor, sea al principio, final, o en cualquier parte.
    
    Consulta = Tabla.find({
        "$or":[
            {"idUsuario": regex}, #Aqui solo queda agregar la variable, ésta variable *no* es String, re.compile le ha indicado a Python que el contenido de la variable es Expresion Regular(regex)
            {"nombreUsuario": regex},
            {"emailUsuario": regex},
            {"telefonoUsuario": regex},
            {"edadUsuario": regex}
        ]
    })
    

    :)

    I hope it will be useful also for others.

        
    answered by 15.09.2017 / 16:21
    source