Groups documents by some specified expression and outputs to the next
stage a document for each distinct grouping.

@see http://docs.mongodb.org/manual/reference/operator/aggregation/group/
501417
public function group() : Stage\Group
    {
        $stage = new Stage\Group($this);
        $this->addStage($stage);

        return $stage;
    }
731139
public function groupBy(...$groups)
    {
        foreach (func_get_args() as $arg) {
            $this->query->group($arg)->ungroup()->map(function ($doc) {
                return $doc('reduction')->nth(0);
            });
        }

        return $this;
    }
98704
def aggregate!(ts = Time.now.floor)
      unless self.ancestors.include?MongoMapper::Document
        raise NoMethodError, "aggregate! not defined for this counter"
      end

      aggr = aggregate(ts)
      aggr.each do |_ts, counterVals|
        counterVals.each do |obj, count|
          args = gen_args_for_instance obj, count, _ts, TYPE_MINUTE
          counter = self.new args
          counter.save!
        end
      end
      call_completion_hook(TYPE_MINUTE, ts)
    end
1038562
public static <E> AbstractGroupExpression<E, Set<E>> set(Expression<E> expression) {
        return GSet.createLinked(expression);
    }
1297352
public function groupBy($field)
    {
        $field = $this->addTablePrefix($field);
        $this->addStatement('groupBys', $field);
        return $this;
    }
165019
def select_distinct_field(col, field_or_fields, filters=None):
    
    fields = _preprocess_field_or_fields(field_or_fields)

    if filters is None:
        filters = dict()

    if len(fields) == 1:
        key = fields[0]
        data = list(col.find(filters).distinct(key))
        return data
    else:
        pipeline = [
            {
                "$match": filters
            },
            {
                "$group": {
                    "_id": {key: "$" + key for key in fields},
                },
            },
        ]
        data = list()
        for doc in col.aggregate(pipeline):
            # doc = {"_id": {"a": 0, "b": 0}} ...
            data.append([doc["_id"][key] for key in fields])
        return data
296485
public void execute(@NonNull Document document) {
      for (CaduceusRule rule : rules) {
         TokenMatcher matcher = rule.getRegex().matcher(document);
         while (matcher.find()) {
            ArrayListMultimap<String, Annotation> groups = ArrayListMultimap.create();
            ArrayListMultimap<CaduceusAnnotationProvider, Annotation> providers = ArrayListMultimap.create();

            //Process all the annotation providers
            rule.getAnnotationProviders().forEach(ap -> {
               if (ap.getGroup().equals("*")) {
                  Annotation annotation = createOrGet(document, ap.getAnnotationType(), matcher.group(),
                                                      ap.getAttributes());
                  groups.put(ap.getGroup(), annotation);
                  providers.put(ap, annotation);
               } else {
                  matcher.group(ap.getGroup()).forEach(g -> {
                     Annotation annotation = createOrGet(document, ap.getAnnotationType(), g, ap.getAttributes());
                     groups.put(ap.getGroup(), annotation);
                     providers.put(ap, annotation);
                  });
               }
            });

            if (!groups.containsKey("*")) {
               groups.putAll("*", matcher.group().tokens());
            }


            HashMultimap<String, Tuple2<Annotation, Relation>> relations = HashMultimap.create();
            for (CaduceusRelationProvider rp : rule.getRelationProviders()) {
               List<Annotation> sourceAnnotations = rp.getSource().getAnnotations(groups, matcher);
               List<Annotation> targetAnnotations = rp.getTarget().getAnnotations(groups, matcher);
               for (Annotation source : sourceAnnotations) {
                  for (Annotation target : targetAnnotations) {
                     relations.put(rp.getName(), Tuple2.of(source,
                                                           new Relation(rp.getRelationType(), rp.getRelationValue(),
                                                                        target.getId())));
                     if (rp.isReciprocal()) {
                        relations.put(rp.getName(), Tuple2.of(target,
                                                              new Relation(rp.getRelationType(), rp.getRelationValue(),
                                                                           source.getId())));
                     }
                  }
               }
            }


            Set<String> finalRelations = new HashSet<>();
            rule.getRelationProviders().stream()
                .filter(rp -> StringUtils.isNullOrBlank(rp.getRequires()) || relations.containsKey(rp.getRequires()))
                .forEach(rp -> {
                   relations.get(rp.getName()).forEach(t -> {
                      t.getV1().add(t.getV2());
                      finalRelations.add(rp.getName());
                   });
                });

            providers.entries().stream()
                     .filter(entry -> !finalRelations.containsAll(entry.getKey().getRequires()))
                     .forEach(entry -> document.remove(entry.getValue()));

         }
      }


   }
262998
@JsonIgnore
    public Map<String, Set<String>> getGroupingSpecification() {
        Map<String, Set<String>> result = new LinkedHashMap<>();
        if (!StringUtils.isBlank(grouping)) {
            String[] groups = split(grouping, '|');
            for (String group : groups) {
                String[] groupSpec = split(group.trim(), '=');
                if (groupSpec.length != 2) throw new ExportRequestGroupingFormatException(grouping);
                String groupName = groupSpec[0].trim();
                result.put(
                        groupName,
                        Sets.newLinkedHashSet(
                                Arrays.asList(
                                        split(groupSpec[1].trim(), ',')
                                ).stream()
                                        .map(String::trim)
                                        .collect(Collectors.toList())
                        )
                );
            }
        }
        return result;
    }
187017
public function add($documents)
    {

        $pendingRemove = $this->getRemove();
        if ($this->getRemove()) {
            if ($this->all()) {
                throw new \RuntimeException('Adding to group with pending remove is not permitted');
            } else {
                $this->clearAdd();
                $this->clearRemove();
                $this->saved = array();
            }
        }
        if (!is_array($documents)) {
            $documents = array($documents);
        }

        $add =& $this->getArchive()->getByRef('add', array());
        foreach ($documents as $document) {
            $add[] = $document;
        }
    }
1361118
public function groupConcatSet( $expr, $alias=null, $separator=null, $distinct=null, $order=null )
	{
		debug_assert(
			is_string($expr) || is_array($expr) || (is_object($expr) && $expr instanceof Zend_Db_Expr),
			"Invalid expression value `".var_dump_human_compact($expr)."`"
		);
		debug_assert(
			is_null($alias) || is_string($alias),
			"Invalid alias value `".var_dump_human_compact($alias)."`"
		);
		debug_assert(
			is_null($separator) || is_string($separator),
			"Invalid separator value `".var_dump_human_compact($separator)."`"
		);
		debug_assert(
			is_null($distinct) || is_bool($distinct),
			"Invalid distinct value `".var_dump_human_compact($distinct)."`"
		);
		debug_assert(
			is_null($order) || is_array($order) || is_int($order) || is_string($order) || (is_object($order) && $order instanceof Zend_Db_Expr),
			"Invalid order value `".var_dump_human_compact($order)."`"
		);
		$convertToString = function($expr)
		{
			if( is_object($expr) )
			{
				$expr = strval($expr);
			}
			else
			{
				if( array_key_exists( $expr, $this->schemaColumnsGet() ) )
				{
					$expr = str_wrap($this->getAlias(),'`').'.'.str_wrap( $expr, '`' );
				}
				elseif( is_string($expr) )
				{
					$expr = str_wrap( $expr, '\'' );
				}
			}
			return $expr;
		};
		if( is_array($expr) )
		{
			$expr = array_chain(
				$expr,
				array_map_val_dg( tuple_get( 0, $convertToString ) ),
				array_implode_dg(',')
			);
		}
		else
		{
			$expr = $convertToString( strval($expr) );
		}
		if( $distinct!==null )
		{
			$expr = "DISTINCT {$expr}";
		}
		if( $order!==null )
		{
			if( is_array($order) )
			{
				$order = array_chain(
					$expr,
					array_map_val_dg( tuple_get( 0, $convertToString ) ),
					array_implode_dg(',')
				);
			}
			else
			{
				$order = $convertToString( strval($order) );
			}
			$expr = "{$expr} ORDER BY {$order}";
		}
		if( $separator!==null )
		{
			$expr = "{$expr} SEPARATOR '{$separator}'";
		}
		$expr = "GROUP_CONCAT({$expr})";
		if( $alias!==null )
		{
			$expr = [$alias=>$expr];
		}
		return $this->setColumns( $expr, $this->getAlias() );
	}
889486
public function groupBy($fields)
    {
        if (!is_array($fields)) {
            $fields = $this->splitParts($fields);
        }

        foreach ($fields as $k => $field) {
            $fields[$k] = $this->db->quoteColumn($field);
        }

        $this->query['group'] = implode(',', $fields);

        return $this;
    }
395968
public Query groupby(final Collection<? extends Expression> groupbyColumns) {
        if (groupbyColumns == null) {
            return this;
        }

        this.groupbyColumns.addAll(groupbyColumns);

        return this;
    }
1284899
public function group($field, $id)
    {
        if (!isset($this->grouped[$field])) {
            foreach ($this->rows as $row) {
                if (!isset($this->grouped[$field][$row->$field])) {
                    $this->grouped[$field][$row->$field] = [];
                }
                $this->grouped[$field][$row->$field][] = $row;
            }
        }
        $origins = isset($this->grouped[$field][$id]) ? $this->grouped[$field][$id] : [];
        return new Rows($origins, $this->getTable(), $this, $this->model);
    }
952354
private List<Document> getDistinctCountGroup() {
		// propertyPath is null when the query is a select on an entity
		// In this case we can make the distinct on the id of the document
		Object groupColumn = propertyPath == null ? "$_id" : propertyPath;
		Document group = new Document();
		group.append( "$group", new Document( "_id", groupColumn ) );

		Document groupSum = new Document();
		groupSum.append( "$group", new Document()
				.append( "_id", propertyPath )
				.append( PROJECTION_FIELD, new Document( "$sum", 1 ) ) );
		return Arrays.asList( group, groupSum );
	}
172193
def group_by(self, *args):
        
        if len(args) == 1:
            self.raw_fields_group = args[0].split(',')
        else:
            self.raw_fields_group = list(args)
        return self
1186292
private AggregationBuilder appendAggregation(CollectionExpression collectionExpression,
            EntityMetadata entityMetadata, AggregationBuilder aggregationBuilder)
    {
        ListIterable<Expression> functionlist = collectionExpression.children();
        for (Expression function : functionlist)
        {
            if (isAggregationExpression(function) && checkIfKeyExists(function.toParsedText()))
            {
                aggregationBuilder.subAggregation(getMetricsAggregation(function, entityMetadata));
            }
        }
        return aggregationBuilder;
    }
1071645
def action_aggregate(reader, *args):
    """"""
    all_aggregated = aggregated_records(reader)
    first_row = next(all_aggregated)
    keys = sorted(first_row.keys())
    print(*keys, sep='\t')

    # Join the first row with the rest of the rows and print them
    iterable = chain([first_row], all_aggregated)
    for item in iterable:
        print(*[item[k] for k in keys], sep='\t')