2016-12-11 62 views
0

我需要知道如何在mongodb中查找查询,如果不知道具体查询有多少个参数。多变量查询查找mongodb

例子:

@get('/find_users') 
def find_users(): 

# The posibilities are 
# http://localhost:8080find_users?name=Andrew   
# http://localhost:8080/find_users?name=Andrew&surname=Sun 

db = mongoClient['bdname'] 
coleccion = db['users'] 
dicc = request.query.decode() 

username = "" 
firstsurname = "" 

for item in dicc:  
    if item == "name": 
     username = request.query.name 
    elif item == "surname": 
     firstsurname = request.query.surname 

d = coleccion.find({'name':username, 'surname':username}) 

for item in d: 
    print(item['name']) 
    print(item['surname']) 

有了这个查询,如果我只按名称查找用户,姓取一个字符串,空,结果犯规正确

回答

1

ExpressJS docs

request.query是包含路由中每个查询字符串参数的属性的对象。

因此,换句话说,您不必解码request.query

当您向http://localhost:8080find_users?name=Andrew发出请求时,您的request.query对象将是{"name":"Andrew"}

当您向http://localhost:8080find_users?name=Andrew&surname=Sun发出请求时,那么您的request.query对象将为{"name":"Andrew", "surname": "Sun"}

查询对象上的属性被映射到来自请求url的查询字符串参数。您不必确切知道查询中有多少个参数。当查询字符串参数更改时,查询对象属性会更改。你可以使用这个对象来执行数据库搜索:

var findOptions = request.query; 

collection.find(findOptions); 

这样,你不会有姓取一个空字符串和搞乱了结果的问题。如果surname不是查询字符串参数的一部分,则该对象将不包含surname属性,并且数据库搜索将在搜索过程中忽略此字段。