I have the following code that searches for a record in the MongoDB database based on user information from an HTML form :
# -*- 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)
The user information reaches User_data through REQUEST
To data I assign the value that interests me from the submitted form, in this case it is find :
<input type="text" name="find">
In Data and Table the connection to the CRUD database and the users table are linked
Query contains the query to be performed, and this is what fails.
In the database I have:
/* 1 */
{
"_id" : ObjectId("59b9a5837a264d076dd40a12"),
"idUsuario" : "1093796198",
"nombreUsuario" : "Martín Bermú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 for example: a document number of some user that may or may not exist in the records. So I just type 1093 and send the information.
- I must look for that 1093 in all the fields or the fields that I have defined for their respective search, in this case idUser , nameUser , emailUser , phoneUser and finally ageUser .
- To perform the query, there should be an " OR " and then a " LIKE " for each field which indicates that it searches for records that contain , start , or end with the given characters, in this case: 1093
As far as I understand for MongoDB a regular expression is not a String. MongoDB takes strings literally, so it won't look at them for RegExp.
So Python doesn't know what type of variable I'm trying to search for because it would then be /data/ , that's not valid for Python. Being '/dato/' (take into account the quotes) it would be correct, but it is not for MongoDB
The query fails, finds nothing.
What solution or alternative is there for this problem?
(And of course, I know that in MongoDB there is no OR as such, nor LIKE, I'm looking for an equivalence that can lead me to do the same thing.)
I found the answer:
Re must be imported, this way we can tell Python to treat the variable as a Regular Expression.
:)
I hope it will be useful for others too.