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