在MongoDB中,如何链接find()
方法?假设我想在Python / pymongo中做这样的事情
query = prices.find({'symbol': "AAPL"})
if start is not None:
query = query.find({'date': {'$gte': start}})
if end is not None:
query = query.find({'date': {'$lte': end}})
答案 0 :(得分:6)
您无法链接查找方法。调用find
将返回Cursor对象。您可能想要构建一个查询,然后调用find:
from collections import OrderedDict
query = OrderedDict([('symbol', 'AAPL')])
if start is not None:
query['date'] = {'$gte': start}
if end is not None:
query['date'] = {'$lte': end}
cursor = prices.find(query)
答案 1 :(得分:3)
如果你真的喜欢链接的概念,你可以轻松支持filter
表达式的链接,而不是整个查询/光标。类似的东西:
class FilterExpression(dict):
def __call__(self, key, cond):
e = type(self)(self)
e.update({key: cond})
return e
f = FilterExpression({'symbol': "AAPL"})
if start is not None:
f = f('date', {'$gte': start})
if end is not None:
f = f('date', {'$lte': end})
query = prices.find(f)
由于FilterExpression
是dict
的子类(即 IS-A dict),因此您可以将其传递给find
而不先将其转换。