在pymongo中动态构建查询

use*_*826 0 python mongodb pymongo

我有一个网页,用户可以在地图上查看MongoDB中的数据.我想要几个复选框,单选按钮等来过滤地图上看到的内容.如果我使用MySQL,我会这样做

query = "SELECT * FROM table WHERE x = 1" 
if checkbox == "checked":
  query += "AND WHERE y = 2"
Run Code Online (Sandbox Code Playgroud)

我怎么能用pymongo复制它?

Tre*_*vor 6

您只需构建查询dict:

query = {'x': 1}
if checkbox == 'checked':
    query['y'] = 2

results = db.collection.find(query)
Run Code Online (Sandbox Code Playgroud)

执行OR查询将如下所示:

query = [{'x': 1}]
if checkbox == 'checked':
    query.append({'y': 2})

results = db.collection.find({'$or': query})
Run Code Online (Sandbox Code Playgroud)