Aggregation Nates
Aggregation Nates
_id: 1,
name: "Alice",
scores: [
},
_id: 2,
name: "Bob",
scores: [
},
_id: 3,
name: "Charlie",
scores: [
]
Exercises:
Aggregation:
db.Student_database.aggregate([
$group: {
_id: "$name",
count: { $sum: 1 }
])
db.Student_database.aggregate([
$group: {
_id: "$name",
])
3. Find the Maximum Score of Each Student:
db.Student_database.aggregate([
$group: {
_id: "$name",
])
db.Student_database.aggregate([
$group: {
_id: "$name",
])
Purpose of the Aggregation
The purpose of this aggregation pipeline is to group documents in the collection by the `name` field
and count the number of documents for each unique `name`.
Aggregation Pipeline
db.collection.aggregate([
$group: {
_id: "$name",
count: { $sum: 1 }
])
1. `db.collection.aggregate([...])`
2. `$group` Stage
- The `$group` stage is used to group documents by a specified key and perform aggregation
operations on the grouped data.
3. `_id: "$name"`
- The `_id` field in the `$group` stage is used to specify the key by which to group the documents.
- Here, `"$name"` means that documents will be grouped by the value of the `name` field.
4. `count: { $sum: 1 }`
- For each document in a group, `1` will be added to the sum, effectively counting the number of
documents in each group.
Result
The result of this aggregation will be a document for each unique `name`, with a field `count` that
shows the number of documents with that `name`.
Example
json DataSet
```json
```
Summary
- Counting: The `count` field indicates how many documents there are for each `name`.
- Output: Each document in the result represents a unique `name` and the count of occurrences of
that `name` in the original collection.
EXAMPLE -2
Example 1: Counting Documents by a Specific Field
Goal: Count the number of documents for each unique value in the `category` field.
Sample Data:
```json
```
Aggregation Pipeline:
```json
db.collection.aggregate([
$group: {
_id: "$category",
count: { $sum: 1 }
}
}
])
```
Explanation:
- Count the number of documents in each category by summing `1` for each document.
Result:
```json
```
Sample Data:
```json
```
Aggregation Pipeline:
```json
db.collection.aggregate([
$group: {
_id: "$product",
])
```
Explanation:
Result:
```json
```
```json
```
Aggregation Pipeline:
```json
db.collection.aggregate([
$group: {
_id: "$student",
])
```
Explanation:
Result:
```json
```
Sample Data:
```json
```
Aggregation Pipeline:
```json
db.collection.aggregate([
$group: {
_id: "$subject",
])
```
Explanation:
Result:
```json
```
Sample Data:
```json
```
Aggregation Pipeline:
```json
db.collection.aggregate([
$group: {
_id: "$student",
])
```
Explanation:
Result:
```json
```