在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}})
发布于 2014-04-23 14:06:57
你找不到方法。调用find
将返回游标对象。您可能希望构建一个查询,然后调用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)
发布于 2014-04-24 05:21:31
如果您真的喜欢链接的概念,那么可以轻松地支持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
,而无需首先转换它。
https://stackoverflow.com/questions/23245880
复制相似问题