Creates aggregation pipeline for aggregation
            :param collection: Mongo collection for aggregation
            :type  collection: MongoCollection

            :return pipeline: list of dicts
517420
def build_pipeline(self, collection):
        
        pipeline = []

        if isinstance(collection.where_dict, dict) and collection.where_dict:
            match_dict = {
                "$match": collection.where_dict
            }
            pipeline.append(match_dict)

        group_keys_dict = self.build_mongo_doc(self.join_keys)
        push_dict = self.build_mongo_doc(collection.select_keys)

        group_by_dict = {
            "$group":
                {
                    "_id": group_keys_dict,
                    "docs": {
                        "$push": push_dict
                    }
                }
        }

        pipeline.append(group_by_dict)

        return pipeline
586228
public static <T> JSONArray toJSONArray(final Collection<T> collection) {
        final JSONArray ret = new JSONArray();

        if (null == collection) {
            return ret;
        }

        for (final T object : collection) {
            ret.put(object);
        }

        return ret;
    }
229311
public static <T, R> Map<R, List<T>> groupBy(Collection<T> collection,
            Function<T, R> classifier) {
        return groupBy(collection.stream(), classifier);
    }
7503
def multi_groupby(self, key_fn):
        
        result_dict = defaultdict(list)

        for x in self:
            for key in key_fn(x):
                result_dict[key].append(x)

        # convert result lists into same Collection type as this one
        return {
            k: self.clone_with_new_elements(elements)
            for (k, elements)
            in result_dict.items()
        }
695858
def partitions(collection):
    
    collection = list(collection)

    # Special cases
    if not collection:
        return

    if len(collection) == 1:
        yield [collection]
        return

    first = collection[0]
    for smaller in partitions(collection[1:]):
        for n, subset in enumerate(smaller):
            yield smaller[:n] + [[first] + subset] + smaller[n+1:]
        yield [[first]] + smaller
354205
def get_collection(self, **kwargs):
        
        from pymongo import MongoClient

        if self.host and self.port:
            client = MongoClient(host=config.host, port=config.port)
        else:
            client = MongoClient()
        db = client[self.dbname]

        # Authenticate if needed
        if self.user and self.password:
            db.autenticate(self.user, password=self.password)

        return db[self.collection]
136805
def _build_collections(store):
    """"""

    result = {}

    client = pymongo.MongoClient(host=dbhost, port=dbport)
    db = client[dbname]

    for schemaname in store:

        schema = None
        indices = None

        try:
            schema = store[schemaname]['schema']
            indices = store[schemaname].get('indices', None)
        except KeyError:
            db_log("No schema found for ", schemaname, lvl=critical)

        try:
            result[schemaname] = db[schemaname]
        except Exception:
            db_log("Could not get collection for schema ", schemaname, schema, lvl=critical, exc=True)

        if indices is not None:
            col = db[schemaname]
            db_log('Adding indices to', schemaname, lvl=debug)
            i = 0
            keys = list(indices.keys())

            while i < len(indices):
                index_name = keys[i]
                index = indices[index_name]

                index_type = index.get('type', None)
                index_unique = index.get('unique', False)
                index_sparse = index.get('sparse', True)
                index_reindex = index.get('reindex', False)

                if index_type in (None, 'text'):
                    index_type = pymongo.TEXT
                elif index_type == '2dsphere':
                    index_type = pymongo.GEOSPHERE

                def do_index():
                    col.ensure_index([(index_name, index_type)],
                                     unique=index_unique,
                                     sparse=index_sparse)

                db_log('Enabling index of type', index_type, 'on', index_name, lvl=debug)
                try:
                    do_index()
                    i += 1
                except pymongo.errors.OperationFailure:
                    db_log(col.list_indexes().__dict__, pretty=True, lvl=verbose)
                    if not index_reindex:
                        db_log('Index was not created!', lvl=warn)
                        i += 1
                    else:
                        try:
                            col.drop_index(index_name)
                            do_index()
                            i += 1
                        except pymongo.errors.OperationFailure as e:
                            db_log('Index recreation problem:', exc=True, lvl=error)
                            col.drop_indexes()
                            i = 0

                            # for index in col.list_indexes():
                            #    db_log("Index: ", index)
    return result
812837
def get_record_collections(record, matcher):
    
    collections = current_collections.collections
    if collections is None:
        # build collections cache
        collections = current_collections.collections = dict(_build_cache())

    output = set()

    for collections in matcher(collections, record):
        output |= collections

    return list(output)
1046627
def extend(self, collection):
        
        if type(collection) is list:
            if self._col_dict is None and self._col_list is None:
                self._col_list = collection
            else:
                self._col_list += collection
            self._sync_list_to_dict(collection)
        elif type(collection) is dict:
            if self._col_dict is None and self._col_list is None:
                self._col_dict = collection
                self._col_list = collection.values()
            else:
                for key, value in collection.items():
                    self._set_key(key, value)
        else:
            raise NotImplementedError()
682211
def return_collection(collection_type):
    
    def outer_func(func):
        @functools.wraps(func)
        def inner_func(self, *pargs, **kwargs):
            result = func(self, *pargs, **kwargs)
            return list(map(collection_type, result))
        return inner_func
    return outer_func
1035194
public function createFromCollection(Collection $collection)
    {
        $this->operator = new CollectionOperator($collection, $this->request);
        $this->prepare();

        return $this;
    }
1094103
def iterator(self, **kwargs):
        
        cls_name = '{0}Collection'.format(self._cls.__name__)
        collection_cls = type(str(cls_name), (ElementCollection,), {})

        params = {'filter_context': self._cls.typeof}
        params.update(kwargs)
        return collection_cls(**params)
620675
public static <T> List<T> convertCollectionToList(final Collection<T> collection) {

        if(List.class.isAssignableFrom(collection.getClass())) {
            return (List<T>)collection;
        }

        return new ArrayList<>(collection);

    }
154314
function createCollection(proto, objectOnly){
    function Collection(a){
      if (!this || this.constructor !== Collection) return new Collection(a);
      this._keys = [];
      this._values = [];
      this._itp = []; // iteration pointers
      this.objectOnly = objectOnly;

      //parse initial iterable argument passed
      if (a) init.call(this, a);
    }

    //define size for non object-only collections
    if (!objectOnly) {
      defineProperty(proto, 'size', {
        get: sharedSize
      });
    }

    //set prototype
    proto.constructor = Collection;
    Collection.prototype = proto;

    return Collection;
  }
694398
def apply(query, collection=None):
    
    if not collection:
        return query
    result_tree = create_collection_query(collection)
    return AndOp(query, result_tree)
689067
def map_collection(func, collection):
    
    datatype = type(collection)
    if isinstance(collection, Mapping):
        return datatype((key, func(val)) for key, val in collection.items())
    if is_string(collection):
        return collection
    elif isinstance(collection, Iterable):
        return datatype(map(func, collection))
    else:
        return collection
587341
public RemoteAggregateIterable<DocumentT> aggregate(final List<? extends Bson> pipeline) {
    return new RemoteAggregateIterableImpl<>(proxy.aggregate(pipeline), dispatcher);
  }