from pymongo import Connection database collection def __getattr__ sel

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
from pymongo import Connection, database, collection
def __getattr__(self, name):
return Collection(self, name)
database.Database.__getattr__ = __getattr__
database.Database.__getitem__ = __getattr__
class Collection(collection.Collection):
def find(self, _spec=None, **kwargs):
'''
kwargs are preferred way to filtration
_spec is an optional dict, specifying filters.
'''
spec = process_spec(_spec or kwargs)
return super(Collection, self).find(spec=spec)
def process_spec(spec):
new = {}
for k, v in spec.items():
if '__' in k:
k, child = k.split('__', 1)
new.setdefault(k, {}).update(process_spec({fixname(child): v}))
elif k.startswith('_'):
new[k.replace('_', '$', 1)] = v
else:
new[k] = v
return new
def fixname(key):
if key in 'gt lt gte lte ne in nin all size where'.split():
return '$' + key