# MongoDB Aggregation

## Aggregate Framework

* Queries are written inside `[]` operator, denoting the order in which hey execute
* `$group` : An operator that takes in multiple streams of data and distributes it into multiple reservoirs

```bash
# MQL Query
db.listingsAndReviews.find({ "amenities": "Wifi" },
                           { "price": 1, "address": 1, "_id": 0 }).pretty()

# MQL Query ith aggregation framework
db.listingsAndReviews.aggregate(
    [
      { "$match": { "amenities": "Wifi" } },
      { "$project": { "price": 1,
                      "address": 1,
                      "_id": 0 }}
    ]).pretty()
```

```bash
# Find one document in the collection 
# and only include the address field in the resulting cursor.
db.listingsAndReviews.findOne({ },{ "address": 1, "_id": 0 })

# Project only the address field value for each document, 
# then group all documents into one document per address.country value.
db.listingsAndReviews.aggregate(
    [   { "$project": { "address": 1, "_id": 0 }},
        { "$group": { "_id": "$address.country" }}
    ])

# Project only the address field value for each document, 
# then group all documents into one document per address.country value, 
# and count one for each document in each group.
db.listingsAndReviews.aggregate(
    [
          { "$project": { "address": 1, "_id": 0 }},
          { "$group": { "_id": "$address.country",
                        "count": { "$sum": 1 } } }
    ])
```


---

# 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://dev117uday.gitbook.io/databases/mongodb/mongodb-aggregation.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.
