【问题标题】:Multiple variable query find mongodb多变量查询查找mongodb
【发布时间】:2017-04-26 17:56:00
【问题描述】:

如果不知道究竟有多少参数有查询,我需要知道如何在 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'])

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

【问题讨论】:

    标签: python mongodb bottle


    【解决方案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 属性,并且数据库搜索将在搜索过程中忽略该字段。

    【讨论】:

      猜你喜欢
      • 2015-06-24
      • 2021-07-19
      • 2016-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多