Question

In MongoDB how do you chain find() methods? Suppose I want to do something like this in 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}})
Was it helpful?

Solution

You can't chain find methods. Calling find will return the Cursor object. You probably want to build a query and then call 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)

OTHER TIPS

If you really like the notion of chaining, you can easily support chaining of the filter expression, instead of the whole query/cursor. Something like:

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)

Since FilterExpression is a subclass of dict (i.e. IS-A dict), you can pass it to find without converting it first.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top