2 回答

TA貢獻1777條經驗 獲得超10個贊
編輯:
對于多個過濾器:
filter = {}
if price is not None: filter['price'] = {'$lt' : price }
if quantity is not None: filter['quantity'] = {'$lt' : quantity }
if volume is not None: filter['volume'] = {'$lt' : volume }
posts = db.testcollection.find(filter)
原件:
試試這個,以免自己在布爾邏輯世界中有點發瘋:
if price is None:
filter = {}
else:
filter = {'price' : {'$lt' : price }}
posts = db.collection.find(filter)

TA貢獻1883條經驗 獲得超3個贊
如果你想從前端傳遞一個數組(使用查詢參數),你可以使用 mongodb 的 $in 參數: URL 參數在數組中作為 JSON 對象發送:
/read?job_type%5B%5D=Full%20Time&job_type%5B%5D=Part%20Time&country%5B%5D=Germany&country%5B%5D=China
@app.route("/read", methods=['GET', 'POST'])
def read():
job_type = request.args.getlist('job_type[]')
country = request.args.getlist('country[]')
filter = {}
if len(job_type) > 0: filter['job_type'] = {'$in': job_type}
if len(country) > 0: filter['country'] = {'$in': country}
jobs = db_operations.find(filter)
添加回答
舉報