def __init__(self, database, collection, spec_or_id=None, fields=None, snapshot=False, tailable=False, max_scan=None, is_command=False, explain=False, hint=None, skip=0, limit=0, sort=None, connection=None, read_preference=None, timeout=True, slave_okay=True, **kw): if spec_or_id is not None and not isinstance(spec_or_id, dict): spec_or_id = {"_id": spec_or_id} self._spec = spec_or_id or {} if fields is not None: if not fields: fields = {"_id": 1} if not isinstance(fields, dict): fields = helpers._fields_list_to_dict(fields) self._fields = fields self._snapshot = snapshot self._tailable = tailable self._max_scan = max_scan self._hint = hint self._database = database self._collection = collection self._collection_name = database.get_collection_name(collection) self._timeout = timeout self._is_command = is_command self._explain = explain self._slave_okay = slave_okay self._read_preference = read_preference self._connection = connection self._ordering = sort self._skip = skip self._limit = limit
def group(self, key, condition, initial, reduce, finalize=None, read_preference=None, callback=None): """Perform a query similar to an SQL *group by* operation. Returns an array of grouped items. The `key` parameter can be: - ``None`` to use the entire document as a key. - A :class:`list` of keys (each a :class:`basestring` (:class:`str` in python 3)) to group by. - A :class:`basestring` (:class:`str` in python 3), or :class:`~bson.code.Code` instance containing a JavaScript function to be applied to each document, returning the key to group by. :Parameters: - `key`: fields to group by (see above description) - `condition`: specification of rows to be considered (as a :meth:`find` query specification) - `initial`: initial value of the aggregation counter object - `reduce`: aggregation function as a JavaScript string - `finalize`: function to be called on each object in output list. """ group = {} if isinstance(key, basestring): group["$keyf"] = Code(key) elif key is not None: group = {"key": helpers._fields_list_to_dict(key)} group["ns"] = self._collection group["$reduce"] = Code(reduce) group["cond"] = condition group["initial"] = initial if finalize is not None: group["finalize"] = Code(finalize) response, error = yield gen.Task(self._database.command, "group", group, read_preference=read_preference) callback(response)