Skip to content

DOCSP-32718: aggregation code comments #764

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 1, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions source/code-snippets/aggregation/agg.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
// Perform an aggregation

const { MongoClient } = require("mongodb");

const uri = process.env.MONGDODB_URI;
const client = new MongoClient(uri);

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

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

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

// begin aggregation
// Define an aggregation pipeline with a match stage and a group stage
const pipeline = [
{ $match: { categories: "Bakery" } },
{ $group: { _id: "$stars", count: { $sum: 1 } } }
];

// Execute the aggregation
const aggCursor = coll.aggregate(pipeline);

// Print the aggregated results
for await (const doc of aggCursor) {
console.log(doc);
}
// end aggregation
}
// Run the program and print thrown errors, then close the connection
run().catch(console.dir).finally(() => client.close());