Lecture3 - Node.js and JSON Objects(quiz).pdf

Document Details

ExcitingRhodonite3899

Uploaded by ExcitingRhodonite3899

null

Tags

node.js javascript web development

Full Transcript

Background of Node.js ❑ Modern server-side applications (web apps) ➢ Handle a large amount of requests to interact with external services, such as database, memory cache, computing server, or the file system. ➢ Machine programs (threads and processes) must wait for the response of these requests Wai...

Background of Node.js ❑ Modern server-side applications (web apps) ➢ Handle a large amount of requests to interact with external services, such as database, memory cache, computing server, or the file system. ➢ Machine programs (threads and processes) must wait for the response of these requests Waiters really wait carefully: • • • Lots of orders come Each waiter handles one order and just waits for the order to finish He/She does nothing when waiting “Low-efficient services when handling orders!” 5 Blocking I/O problems ❑ Server-side Issues ➢ Overhead when creating new stacks and execution environment, run into the limits of the server’s available memory ➢ I/O recourses are “blocked” because of doing nothing when waiting for the interacting/query responses ➢ Time consuming, and low efficient “Blocking I/O Problems in web apps!” 6 Blocking I/O Blocking Function Calls Every time the server got an order request they had to wait for the bar/kitchen to finish before taking the next request, then the service for this restaurant would be very slow and customers would most likely be unsatisfied. This is how blocking I/O works. 7 Previous Solutions ❑ Configure more servers or memory to increase the number of simultaneous connections Change Restaurant Business: • Employ more waiters ❑ Use smaller, lightweight servers such as Nginx (instead of more powerful and feature-rich HTTP servers such as Apache), • Provide fewer and simple services (reduce the scale of restaurants) ❑ Use stripped-down web programing language such as PHP or Python. • Making easy-finished dishes “Still Blocking I/O, low-efficient waiters” 8 Evolved Solutions ❑ Clean up unwidely APIs by increasing client libraries (such as jQuery, script.aculo.us, or Prototype) Optimize Restaurant Management: • Improve the kitchen in scales and categories • ❑ Develop script-based apps with more dynamic effects • Train waiters to quickly record one order at one time, then switch to another order Waiters serve the dish when it’s ready “How and which script?” 9 From JavaScript to Node.js ❑ 2009, Ryan Dahl uses JavaScript to write web applications ❑ Find JavaScript lacking a robust input/output (I/O) model • • meaning he could run new tasks when waiting for interacting/query responses → achieve non-blocking I/O process multiple requests concurrently within single thread → memory efficient ❑ He took Chrome V8 engine and an event-processing library called libev, and came up with the first “Node.js” 10 WHAT IS Node.js? ❑ Node.js is a JavaScript runtime environment for serverside scripting • • Write and run non-blocking Node.js apps Produce dynamic web page content http://nodejs.org/ 11 Workflow of Node.js • • Node.js apps are like restaurants processing orders (requests). The operating system is like the bar/kitchen to handle requests. Orders (requests) come, Node.js will 1. process the request one-by-one and record them in an event stack 2. tell system to handle all requests, use call-back functions to notify the response 3. don’t wait, switch to process another order (non-blocking) 4. once the system returns the request for an event, a call-back appears to response for this event 12 Non-Blocking I/O Callback functions The callback functions passed as arguments are invoked asynchronously when the return value from their respective I/O calls is available. 13 Callbacks and Event Loop ❑ A typical Node.js app is basically a collection of callbacks that are executed in reaction to various events: an incoming connection, I/O completion, timeout expiry, etc.. ❑ Event-loop is a single main thread that executes all these call-backs, and thus call-backs should be quick to complete as all other pending call-backs are waiting for their turn. 14 Properties of Node.js ❑ Node.js is event-driven, single-threaded, non-blocking, and asynchronously programming, which is very memory efficient. 15 Pros and Cons of Node.js* Pros and Cons: ✓ Centered around applications that are doing lots of different things with lots of different processes, servers, or services. ✓ Handling huge connections to databases, caching servers, file systems, application servers, and more. ❖ Not an optimal environment for writing compute servers that are doing serious, long-running computations, Node’s model of a single thread in a single process can create problems Suggestions: ➢ Carefully schedule resources when doing more computationally intensive work ➢ Perhaps consider farming those tasks out to other platforms and run them as a service for your Node.js programs to call. 16 Node.js files ❑ Node.js files contain tasks (event stack and callbacks) that will be executed on certain events ❑ Node.js files must be initiated (runninig) on a server before having any effect ❑ Node.js files have extension ".js" 17 A Node.js file // helloServer.js var http = require('http'); helloServer = http.createServer(function(req,res) { res.writeHead(200, {'Content-Type': 'text/html'}); res.write("<html><head>"); res.write("<title>Hello World Page</title>"); res.write("</head>"); res.write("<body><H1>Hello World!</H1></body>"); res.end("</html>"); }); helloServer.listen(8099); node helloServer.js Type this in the terminal to run helloServer.js; To Stop: Press Ctrl-C No Web/Application Server!!! (no Apache, Tomcat & etc.) 18 What can Node.js do? ❑ Node.js can generate dynamic page content ❑ Node.js can create, open, read, write, delete, and close files on the server ❑ Node.js can collect form data ❑ Node.js can add, delete, modify data in your database ❑ And many more… Source: https://www.w3schools.com/nodejs/nodejs_intro.asp 19 Review of JavaScript JS ON COMPS381F 20 Data Types ❑ Data types in JavaScript ❑ Basic types: Number, Boolean, String, Object (JSON) ❑ Complex objects: Array, Function ❑ Special Objects: Null and Undefined • Null is an explicit assertion that “there is no value” • Undefined means that a value has not been set yet or simply does not exist 21 Numbers ❑ All numbers in JavaScript are 64-bit IEEE 754 double-precision floating-point numbers. ❑ For all positive and negative integers that can be expressed in 2 53 bits ❑ Caution: For many numeric values, it is an approximation of the actual number! May consider using the string type if approximation causes problems 22 Numbers ❑ Dividing a number by zero returns the value Infinity or –Infinity instead of generating a runtime exception ❑ Use functions parseInt and parseFloat to convert strings to numbers 23 Numbers NaN means “not a number” 24 Boolean ❑ Boolean data types: false and true ❑ These data evaluate to false: 0 , empty strings ("") , NaN, null, and undefined • NaN means “not a number” • Null is an explicit assertion that “there is no value” • Undefined means that a value has not been set yet or simply does not exist ❑ All other values evaluate to true. 25 Constants ❑ Before ES6, most values of JavaScript are stored in variables. Creating constants is to use uppercase letters for variable declarations: ❑ ES6 introduced the declaration const and let as ways to create variables with different intentions. 26 Reference: “https://www.freecodecamp.org/news/when-to-capitalize-your-javascript-constants-4fabc0a4a4c4/” Strings ❑ Strings in JavaScript are sequences of Unicode characters (represented internally in a 16-bit UCS-2 format) ❑ No separate char or character data type ❑ Strings can be wrapped in single or double quotation marks ❑ Use \ ’ and \ ” to represent the single or double quotation marks in a string 27 Strings ❑ Use the + operator to add two strings together 28 String Functions (optional)* ❑ Use function indexOf to find a string in another string ❑ Use functions substr or slice to extract a substring form a string 29 String Functions (optional)* ❑ Use function split to split a string into component strings ❑ Use functions trim to remove whitespace from the beginning and end of a string 30 Regular Expressions (optional)* ❑ Replace function replace all sequences of substring in a string function returns the index of the first match, or -1 if no match ❑ Search 31 Object & JSON ❑ Use function JSON.parse to convert a JSON string to an object ❑ Use function JSON.stringify to convert an object to its JSON string representation 32 Object Modification ❑ Adding and deleting object properties 33 Arrays 34 Array Operations ❑ Use function push to add an item to the end of an array ❑ Use function pop to remove an item from the end of an array 35 Array Operations (optional)* Value at index 2 still “exists” and has been set to undefined Use function splice to truly delete an item from an array • It takes an index and number of items to delete 36 Array Operations (optional)* ❑ Use function unshift or shift to insert or delete items from the front of an array, respectively ❑ Use function sort to sort items in an array 37 Array Operations (optional)* ❑ Write your own sort function… Customized Sort 38 Functions ❑ JavaScript is a functional programming language , wherein functions are fully typed objects that can be manipulated, extended, and passes around as data ❑ Node.js takes advantage of this capability, and you will use it extensively in your network and web applications Reference: “https://www.w3schools.com/js/js_function_definition.asp” 39 Anonymous Function ❑ Anonymous function (aka nameless function) • Drawback is difficult to debug Reference: “https://www.w3schools.com/js/js_function_definition.asp” 40 Errors & Exceptions ❑ Errors are sent using an Error object and a message ❑ Catch errors using try/catch construct 41 Controlling Program Flow ❑ Selection structure: • the single-selection structure (if), • the double-selection structure (if/else), • the inline ternary operator (? :) • the multiple-selection structure (switch). ❑ Repetition structure: • an expression is tested at the top of the loop ( while), • an expression is tested at the bottom of the loop (do/while), • operate on each of an object's properties (for/in), • counter controlled repetition (for). 42 If-else Statement (if) if( myVariable == 2 ) { myVariable = 1; } else if( myVariable == 5 ) { myVariable = 3; } else { myVariable = 4; } 43 Conditional Operator ((? :))) var AMorPM = (theHour >= 12) ? "PM" : "AM"; 44 Switch Statement (switch) switch(myVar) { case 1: //if myVar is 1 this is executed case 'sample': //if myVar is 'sample' (or 1, see the next paragraph) //this is executed case false: //if myVar is false (or 1 or 'sample', see the next paragraph) //this is executed default: //if myVar does not satisfy any case, (or if it is //1 or 'sample' or false, see the next paragraph) //this is executed } Reference: “https://www.w3schools.com/js/js_switch.asp” 45 While Loop var myVariable = 1; while( myVariable <= 5 ) { myArray[myVariable] = 1; myVariable++; } Reference: “https://www.w3schools.com/js/js_loop_while.asp” 46 Do While Loop var myVariable = 1; do { myArray[myVariable] = 1; myVariable++; } while( myVariable <= 5 ); Reference: “https://www.w3schools.com/js/js_loop_while.asp” 47 For Loop // Set a limit of 10 on the loop. var howFar = 10; // Create an array called sum with 10 members, 0 through 9. var sum = new Array(howFar); sum[0] = 0; // Iterate from 0 through 9. var theSum = 0; for(var icount = 0; icount < howFar; icount++) { theSum += icount; sum[icount] = theSum; } Reference: “https://www.w3schools.com/js/js_loop_for.asp” 48 For/In Loop // Create an object with some properties var myObject = new Object(); myObject.name = "James"; myObject.age = "22"; myObject.phone = "555 1234"; // Enumerate (loop through)_all the properties in the object for (var prop in myObject) { // This displays "The property 'name' is James", etc. document.write("The property '" + prop + "' is " + myObject[prop]); // New line. document.write("<br />"); } Reference: “https://www.w3schools.com/js/js_loop_forin.asp” 49 Use Node.js to JS ON handle JSON objects COMPS381F 50 JSON Example: Employee Objects <employees> <employee> <firstName>John</firstName> <lastName>Doe</lastName> </employee> <employee> <firstName>Anna</firstName> <lastName>Smith</lastName> </employee> <employee> <firstName>Peter</firstName> <lastName>Jones</lastName> </employee> </employees> {"employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} JSON: an array of 3 employee objects ]} 51 JSON Variables var employee = { "firstName":"John", "lastName":"Doe" }; console.log(employee.firstName); var employees = [ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ]; for (x in employees) { console.log(employees[x].firstName); } A JSON object An array of JSON objects 52 JSON – Evaluates to JavaScript Objects (1) var text = '{ "name": "John Johnson", "address": "Oslo West 16", "phone": "12345678" }'; var jobj = JSON.parse(text); Create a JSON object from string console.log("Name is " + jobj.name); console.log("Address is " + jobj.address); console.log("Phone " + jobj.phone); 53 JSON – Evaluates to JavaScript Objects (2) var text = '{"employees":[' + '{"firstName":"John", "lastName":"Doe"},' + '{"firstName":"Anna", "lastName":"Smith"},' + '{"firstName":"Peter", "lastName":"Jones"} ]}’ var jobj = JSON.parse(text); An array of JSON objects Transverse the array for (x in jobj.employees) { console.log(jobj.employees[x].firstName); } 54 Consuming External JSON Resources (1) ❑ OpenWeatherMap (http://openweathermap.org) offers current weather data, which is available in JSON format, for major metropolitan cities ❑ To get weather data for Tokyo, for instance: https://api.openweathermap.org/data/2.5/weather?q=Tokyo,jp&units =metric&appid={API key} ❑ Weather data is returned in JSON format: {"coord":{"lon":139.6917,"lat":35.6895},"weather":[{"id":500,"main":"Rain","des cription":"light rain","icon":"10n"}],"base":"stations","main":{"temp":299.45,"feels_like":299.4 5,"temp_min":297.48,"temp_max":300.68,"pressure":1010,"humidity":78},"visi bility":10000,"wind":{"speed":5.66,"deg":90},"rain":{"1h":0.7},"clouds":{"all":75 },"dt":1695210557,"sys":{"type":2,"id":268105,"country":"JP","sunrise":1695155 221,"sunset":1695199383},"timezone":32400,"id":1850144,"name":"Tokyo","cod ":200} 55 Consuming External JSON Resources (2) var http = require('http'); var options = { host: 'api.openweathermap.org', port: 80, path: '/data/2.5/weather?q=Tokyo,jp&units=metric', method: 'GET' }; Ignore the details of making HTTP calls for now… var temperature = 0.0; var req = http.request(options, function(res) { res.setEncoding('utf8'); res.on('data', function (chunk) { var jsonObj = JSON.parse(chunk); console.log("Current Temp. : " + jsonObj.main.temp); console.log("Max Temp : " + jsonObj.main.temp_max); console.log("Min Temp : " + jsonObj.main.temp_min); }); Extract temp, temp_max & temp_min }); req.on('error', function(e) { console.log('Problem with request: ' + e.message); }); req.end(); 56 Node Package Manager JS ON (NPM) COMPS381F 57 What is NPM ❑ NPM is a package manger for Node.js packages (or modules/libraries) ❑ www.npmjs.com hosts thousands of free packages to download and use ❑ A package in Node.js contains all the files you need for a module ❑ Modules are JavaScript libraries you can include in your project COMPS381F Download a package ❑ Run the command line command npm and tell NPM to download the package you want ❑ NPM creates a folder named node_modules (in your current folder), where the package will be placed. All packages you install subsequently will be placed in this folder ❑ Example: I want to download a package called upper-case ❑ npm install upper-case COMPS381F Using a package ❑ Once the package is installed, it is ready to use. ❑ Include the package in your Node.js server var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); res.write(("Hello World!").toUpperCase()); res.end(); COMPS381F }).listen(8099); Documentation: https://www.npmjs.com/package/upper-case More packages … url https://www.npmjs.com/package/url formiable https://www.npmjs.com/package/formidable COMPS381F Node.js MongoDB Driver JS ON COMPS381F 62 Install MongoDB Node.js Driver ◾ Do one of the followings: 1. Use npm to install the MongoDB Node.js driver. npm install mongodb 2. Use package.json { " name": " server", " description": "A very simple Node.JS MongoDB app", " author": "Raymond SO <[email protected] >", " version": "0.0.1", " dependencies": { " mongodb": ”3.6.5" }, " engine": " node >= 0.10.0", "scripts": {"start": " node server"} } Remember to run npm install to download and install the dependencies. Reference: http://docs.mongodb.org/getting -started/node/client/ 63 Declare MongoClient variable and other variables var MongoClient = require('mongodb').MongoClient; var assert = require('assert'); 64 Write Node.js to connect to MongoDB const const const const MongoClient = require('mongodb').MongoClient; assert = require('assert'); url = ''; dbName = ‘’; Callback runs when connection is established const client = new MongoClient(url); client.connect((err) => { assert.equal(null,err); console.log("Connected successfully to server"); const db = client.db(dbName); /* * CRUD Operations */ client.close(); }); 65 Sample codes: https://github.com/yalin-liu/comps381-2023/blob/main/lab03/nodejs-mongodb-driver/connect/server.js Assert ◾The assert module provides a simple set of assertion tests that can be used to test invariants. ◾The module is intended for internal use by Node.js, but can be used in application code via require('assert'). ◾However, assert is not a testing framework 66 Assert (1) var assert = require('assert'); function add(a,b) { return a + b; } This will not have any output. If you want to see output, you need to make the assertion fail: var answer = add(1,2); assert.equal(3,answer); 67 Assert (2) var assert = require('assert'); function wrongAdd(a,b) { return a - b; } var answer = wrongAdd(1,2); assert.equal(3,answer); assert.js:89 throw new assert.AssertionError({ ^ AssertionError: 3 == -1 at Object.<anonymous> (/Users/wcrso/Temp/assert.js:9:8) at Module._compile (module.js:541:32) at Object.Module._extensions..js (module.js:550:10) at Module.load (module.js:458:32) at tryModuleLoad (module.js:417:12) at Function.Module._load (module.js:409:3) at Module.runMain (module.js:575:10) at run (bootstrap_node.js:352:7) at startup (bootstrap_node.js:144:9) at bootstrap_node.js:467:3 68 Assert (3) var assert = require('assert'); function wrongAdd(a,b) { return a - b; } var answer = wrongAdd(1,2); try { assert.equal(3,answer); } catch (err) { console.error('There is something wrong with wrongAdd()'); console.error(err); } 69 Insert Data with Node.js 2 1 const insertDocument = (db, callback) => { db.collection('books').insertOne( { "name" : "Introduction to Node.js", "author" : "John Dole", "price" : 75.00, “stock“ :0 }, (err, result) => { 3 assert.equal(err, null); console.log("Inserted one document into the books collection."); callback(result); }); }; const client = new MongoClient(url); client.connect((err) => { assert.equal(null,err); console.log("Connected successfully to server"); const db = client.db(dbName); insertDocument(db, () => { client.close(); 4 }); }); 70 Sample codes: https://github.com/yalin-liu/comps381-2023/blob/main/lab03/nodejs-mongodb-driver/insert/server.js Insert Data with Node.js 1. Connect to MongoDB server 2. When the connection to MongoDB server is established, ( via callback ) ▪ ▪ Check connection error(s) Insert document(s) 3. When the insertion is completed, ( via callback ) ▪ ▪ Check insertion error(s) Close MongoDB server connection 71 Insert Data with Node.js ◾You can use the insertOne method and the insertMany methods to add documents to a collection in MongoDB server. ◾If you attempt to add documents to a collection that does not exist, MongoDB will create the collection for you. 72 Query For All Documents in a Collection (1) const findRestaurants = (db, callback) => { let cursor = db.collection('restaurant').find() cursor.forEach((doc) => { console.log(JSON.stringify(doc)); }); callback(); }; const client = new MongoClient(url); client.connect((err) => { assert.equal(null,err); console.log("Connected successfully to server"); const db = client.db(dbName); findRestaurants(db,() => { client.close(); }) To return all documents in a collection, call the find method without a criteria object. }) 73 Sample codes: https://github.com/yalin-liu/comps381-2023/blob/main/lab03/nodejs-mongodb-driver/find/server.js Query For All Documents in a Collection (2) const findRestaurants = (db, callback) => { let cursor = db.collection('restaurant').find().limit(10) cursor.toArray((err,docs) => { assert.equal(err,null); callback(docs); }); }; const client = new MongoClient(url); client.connect((err) => { assert.equal(null,err); console.log("Connected successfully to server"); const db = client.db(dbName); findRestaurants(db,(restaurants) => { client.close(); console.log("Disconnected MongoDB server"); console.log(restaurants); }) }) 74 Query By a Top Level Field const findRestaurants = (db, callback) => { let cursor = db.collection('restaurant').find({"borough": "Manhattan" }) .limit(10); cursor.forEach((doc) => { console.log(JSON.stringify(doc)); }); callback(); }; Criteria const client = new MongoClient(url); client.connect((err) => { assert.equal(null,err); console.log("Connected successfully to server"); const db = client.db(dbName); findRestaurants(db,() => { client.close(); }) }) 75 Query by a field in an embedded document const findRestaurants = (db, callback) => { let cursor = db.collection('restaurant’) .find({"address.zipcode": "10075" }) .limit(10); cursor.forEach((doc) => { console.log(JSON.stringify(doc)); }); callback(); address is an }; embedded document of restaurant 76 Query by a field in an array const findRestaurants = (db, callback) => { let cursor = db.collection('restaurant’) .find({"grades.grade": "B"}) .limit(10); cursor.forEach((doc) => { console.log(JSON.stringify(doc)); }); callback(); grades is an array }; 77 Specify Conditions With Operators (1) const findRestaurants = (db, callback) => { let cursor = db.collection('restaurant’) .find({ "grades.score": { $gt: 30 } }) .limit(10); cursor.forEach((doc) => { console.log(JSON.stringify(doc)); }); callback(); }; 78 Specify Conditions With Operators (2) const findRestaurants = (db, callback) => { let cursor = db.collection('restaurant’) .find({ "grades.score": { $lt: 10 } }) .limit(10); cursor.forEach((doc) => { console.log(JSON.stringify(doc)); }); callback(); }; 79 Combine Conditions: Logical And const findRestaurants = (db, callback) => { let cursor = db.collection('restaurant’) .find({ "cuisine": "Italian", "address.zipcode": "10075" }) .limit(10); cursor.forEach((doc) => { console.log(JSON.stringify(doc)); }); callback(); }; 80 Combine Conditions: Logical Or const findRestaurants = (db, callback) => { let cursor = db.collection('restaurant’) .find({ $or: [ {"cuisine": "Italian" }, {"address.zipcode": "10075" } ]}) .limit(10); cursor.forEach((doc) => { console.log(JSON.stringify(doc)); }); callback(); }; 81 Sort Query Results var findRestaurants = function(db, callback) { var cursor =db.collection('restaurants').find(). .sort({"borough": 1, "address.zipcode": 1}); cursor.each(function(err, doc) { assert.equal(err, null); if (doc != null) { console.dir(doc); } else { callback(); } }); }; Retrieve all documents in the restaurants collection, sorted first by the borough field in ascending order, and then, within each borough, by the "address.zipcode" field in ascending order. 82 Sample codes: https://github.com/yalin-liu/comps381-2023/blob/main/lab03/nodejs-mongodb-driver/sort/server.js Update Data With Node.js Criteria const updateRestaurants = (db, callback) => Matching { db.collection('restaurant') one .updateOne( document { "restaurant_id" : "41156888" }, { $set: { "address.street": "East 31st Street" } }, (err, results) => { assert.equal(err,null); console.log(results); callback(); }); }; 83 Sample codes: https://github.com/yalin-liu/comps381-2023/blob/main/lab03/nodejs-mongodb-driver/update/server.js Check Update Result const updateRestaurants = (db, callback) => { db.collection('restaurant') .updateOne( { "restaurant_id" : "41156888" }, { $set: { "address.street": "East 31st Street" } }, (err, results) => { assert.equal(err,null); console.log(results); if (results.result.nModified == 1) { console.log('Update Succeed!'); } else { console.log('Update failed!!'); } callback(); }); }; 84 Update Multiple Documents Criteria Matching multiple documents const updateRestaurants = (db, callback) => { db.collection('restaurant') .updateMany( { ”borough" : ”Manhattan" }, { $set: { ”XXXX": ”YYYY" } }, (err, results) => { assert.equal(err,null); console.log(results); callback(); }); }; 85 Replace A Document const replaceRestaurants = (db, callback) => { db.collection('restaurant') }; .replaceOne( { "restaurant_id" : "41156888" }, { "name": "Unknown" }, (err, results) => { assert.equal(err,null) ; console.log(results); callback(); }); Criteria Matching one document 86 Sample codes: https://github.com/yalin-liu/comps381-2023/blob/main/lab03/nodejs-mongodb-driver/replace/server.js Remove Data With Node.js const deleteRestaurants = (db, callback) => { db.collection('restaurant').deleteOne( { "restaurant_id" : "41156888" }, Criteria Matching (err, results) => { One assert.equal(err,null); Document console.log(results); callback(); } ); }; 87 Sample codes: https://github.com/yalin-liu/comps381-2023/blob/main/lab03/nodejs-mongodb-driver/delete/server.js Data Aggregation With Node.js const aggregateRestaurants = (db, callback) => { let cursor = db.collection('restaurant').aggregate( [ {$group: {"_id": "$borough", "count": {$sum: 1}}} ] ); cursor.forEach((c) => { console.log(c); }) callback(); }; 88 Sample codes: https://github.com/yalin-liu/comps381-2023/blob/main/lab03/nodejs-mongodb-driver/aggregate/server.js Filter And Group Documents const aggregateRestaurants = (db, callback) => { var cursor = db.collection('restaurant').aggregate( [ {$match: {"borough": "Queens", "cuisine": "Brazilian"}}, {$group: {"_id": "$address.zipcode", "count": {$sum: 1}}} ] ).toArray((err, docs) => { assert.equal(err,null); console.log(docs); }); }; 89 Sample codes: https://github.com/yalin-liu/comps381-2023/blob/main/lab03/nodejs-mongodb-driver/filter/server.js

Use Quizgecko on...
Browser
Browser