# Ejemplo $group

## $group: (Contar los documentos agrupados por activo)

* Contar los artículos  agrupados por $activo

| Orden                                                                                            | Salida                                                                                                                                  |
| ------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------- |
| db.articulo.aggregate(\[ {"$group": {"\_id": {"\_activo" : "$activo"}, "total": {"$sum": 1}}} ]) | { "\_id" : { "\_activo" : "si" }, "total" : 1790 }                                      { "\_id" : { "\_activo" : "no" }, "total" : 2 } |

* **aggregateFromDocument()/Cuenta el numero de documentos agrupado por activo**
* Lo agrupamos por activo
* Contar los documentos y colocarlos en la variable cantidad

```java
List<Document> documentList = Arrays.asList(

              new Document("$group",
              new Document("_id", "$" + "activo").append("cantidad", new Document("$sum", 1))));

List<JmoordbResult> list = articuloRepository.aggregateFromDocument(documentList);

            if (list == null || list.isEmpty()) {
                System.out.println("No hay articulos con esa condicion");
            } else {

                list.forEach((a) -> {
                    System.out.println("_id " + a.get("_id") + " Cantidad: " + a.get("cantidad"));
                });

            }
```

## ![](/files/-Lc1WvbbXDuvqq7oihcQ)

*


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://avbravo-2.gitbook.io/jmoordb/capitulo-7-aggregation/capitulo-6-aggregation/ejemplo-andgroup.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
