多变量查询查找 mongodb

Multiple variable query find 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'])

使用此查询,如果我仅按姓名查找用户,则姓氏为空字符串且结果不正确

参见ExpressJS docs

request.query is an object containing a property for each query string parameter in the route.

因此,换句话说,您不必解码 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 属性,数据库搜索将在搜索过程中忽略此字段。