1+ // Perform an aggregation
2+
13const { MongoClient } = require ( "mongodb" ) ;
4+
25const uri = process . env . MONGDODB_URI ;
36const 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
3343run ( ) . catch ( console . dir ) . finally ( ( ) => client . close ( ) ) ;
0 commit comments