MongoDB:链查找()

时间:2014-04-23 13:29:14

标签: python mongodb pymongo

在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}})

2 个答案:

答案 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)

由于FilterExpressiondict的子类(即 IS-A dict),因此您可以将其传递给find而不先将其转换。