1
+ // Perform an aggregation
2
+
1
3
const { MongoClient } = require ( "mongodb" ) ;
4
+
2
5
const uri = process . env . MONGDODB_URI ;
3
6
const client = new MongoClient ( uri ) ;
4
7
@@ -7,6 +10,7 @@ async function run() {
7
10
const db = client . db ( "aggregation" ) ;
8
11
const coll = db . collection ( "restaurants" ) ;
9
12
13
+ // Create sample documents
10
14
const docs = [
11
15
{ stars : 3 , categories : [ "Bakery" , "Sandwiches" ] , name : "Rising Sun Bakery" } ,
12
16
{ stars : 4 , categories : [ "Bakery" , "Cafe" , "Bar" ] , name : "Cafe au Late" } ,
@@ -15,19 +19,25 @@ async function run() {
15
19
{ stars : 4 , categories : [ "Bakery" , "Dessert" ] , name : "Petit Cookie" } ,
16
20
] ;
17
21
22
+ // Insert documents into the restaurants collection
18
23
const result = await coll . insertMany ( docs ) ;
19
24
// end data insertion
20
25
21
26
// begin aggregation
27
+ // Define an aggregation pipeline with a match stage and a group stage
22
28
const pipeline = [
23
29
{ $match : { categories : "Bakery" } } ,
24
30
{ $group : { _id : "$stars" , count : { $sum : 1 } } }
25
31
] ;
26
32
33
+ // Execute the aggregation
27
34
const aggCursor = coll . aggregate ( pipeline ) ;
35
+
36
+ // Print the aggregated results
28
37
for await ( const doc of aggCursor ) {
29
38
console . log ( doc ) ;
30
39
}
31
40
// end aggregation
32
41
}
42
+ // Run the program and print thrown errors, then close the connection
33
43
run ( ) . catch ( console . dir ) . finally ( ( ) => client . close ( ) ) ;
0 commit comments