Skip to content

Commit cf6c4b1

Browse files
authored
DOCSP-32718: aggregation code comments (#764)
* DOCSP-32718: aggregation code comments * fixes
1 parent 62aa2ff commit cf6c4b1

File tree

1 file changed

+10
-0
lines changed
  • source/code-snippets/aggregation

1 file changed

+10
-0
lines changed

source/code-snippets/aggregation/agg.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1+
// Perform an aggregation
2+
13
const { MongoClient } = require("mongodb");
4+
25
const uri = process.env.MONGDODB_URI;
36
const client = new MongoClient(uri);
47

@@ -7,6 +10,7 @@ async function run() {
710
const db = client.db("aggregation");
811
const coll = db.collection("restaurants");
912

13+
// Create sample documents
1014
const docs = [
1115
{ stars: 3, categories: ["Bakery", "Sandwiches"], name: "Rising Sun Bakery" },
1216
{ stars: 4, categories: ["Bakery", "Cafe", "Bar"], name: "Cafe au Late" },
@@ -15,19 +19,25 @@ async function run() {
1519
{ stars: 4, categories: ["Bakery", "Dessert"], name: "Petit Cookie" },
1620
];
1721

22+
// Insert documents into the restaurants collection
1823
const result = await coll.insertMany(docs);
1924
// end data insertion
2025

2126
// begin aggregation
27+
// Define an aggregation pipeline with a match stage and a group stage
2228
const pipeline = [
2329
{ $match: { categories: "Bakery" } },
2430
{ $group: { _id: "$stars", count: { $sum: 1 } } }
2531
];
2632

33+
// Execute the aggregation
2734
const aggCursor = coll.aggregate(pipeline);
35+
36+
// Print the aggregated results
2837
for await (const doc of aggCursor) {
2938
console.log(doc);
3039
}
3140
// end aggregation
3241
}
42+
// Run the program and print thrown errors, then close the connection
3343
run().catch(console.dir).finally(() => client.close());

0 commit comments

Comments
 (0)