Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: Chain find()

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}})
like image 929
Morten Avatar asked Apr 23 '14 13:04

Morten


2 Answers

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)
like image 107
Christian P Avatar answered Nov 02 '22 23:11

Christian P


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.

like image 3
shx2 Avatar answered Nov 02 '22 23:11

shx2