Node & MongoDB – Limiting Records

Node & MongoDB – Limit Records ”; Previous Next To limit the selected documents of a collection, you can use collection.find().limit() methods to select required documents. database.collection(“sampleCollection”).find({}).limit(2).toArray(function(error, result) { if (error) throw error; console.log(result); }); Example Try the following example to select limited documents in a mongodb collection − Copy and paste the following example as mongodb_example.js − const MongoClient = require(”mongodb”).MongoClient; // Prepare URL const url = “mongodb://localhost:27017/”; // make a connection to the database MongoClient.connect(url, function(error, client) { if (error) throw error; console.log(“Connected!”); // Connect to the database const database = client.db(”myDb”); database.collection(“sampleCollection”).find({}).limit(2).toArray(function(error, result) { if (error) throw error; console.log(result); }); // close the connection client.close(); }); Output Execute the mysql_example.js script using node and verify the output. node mongodb_example.js Connected! [ { _id: 60c4bbb40f8c3920a0e30fdd, First_Name: ”Radhika”, Last_Name: ”Sharma”, Date_Of_Birth: ”1995-09-26”, e_mail: ”[email protected]”, phone: ”9000012345” }, { _id: 60c4bbb40f8c3920a0e30fde, First_Name: ”Rachel”, Last_Name: ”Christopher”, Date_Of_Birth: ”1990-02-16”, e_mail: ”[email protected]”, phone: ”9000054321” } ] Print Page Previous Next Advertisements ”;

Node & MongoDB – Update Document

Node & MongoDB – Update Documents ”; Previous Next To update documents of a collection, you can use collection.updateOne() or collection.updateMany() methods to update one or multiple documents. database.collection(“sampleCollection”).updateOne(query,updates, function(error, result) { if (error) throw error; console.log(”Document Updated”); }); database.collection(“sampleCollection”).updateMany(query,updates, function(error, result) { if (error) throw error; console.log(result.result.nModified + ” document(s) updated”); }); Example Try the following example to update a document in a mongodb collection − Copy and paste the following example as mongodb_example.js − const MongoClient = require(”mongodb”).MongoClient; // Prepare URL const url = “mongodb://localhost:27017/”; // make a connection to the database MongoClient.connect(url, function(error, client) { if (error) throw error; console.log(“Connected!”); // Connect to the database const database = client.db(”myDb”); database.collection(“sampleCollection”).updateOne({First_Name:”Mahesh”}, { $set: { e_mail: ”[email protected]” } }, function(error, result) { if (error) throw error; console.log(”Document Updated.”); }); // close the connection client.close(); }); Output Execute the mysql_example.js script using node and verify the output. node mongodb_example.js Connected! Document Updated. Print Page Previous Next Advertisements ”;

Node.js – Useful Resources

Node.js – Useful Resources ”; Previous Next The following resources contain additional information on Node.js. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Nodejs Course with 10 real-world Projects Most Popular 89 Lectures 17 hours Eduonix Learning Solutions More Detail Javascript & jQuery Mastery Course 79 Lectures 6.5 hours Skillbakery More Detail Finest Laravel Course – Learn from 0 to ninja with ReactJS Most Popular 166 Lectures 13 hours Paul Carlo Tordecilla More Detail Angular JS Full Stack: Create and Host Listing/Classified Site 59 Lectures 4 hours Jay R More Detail HTML5 Game Development Course : Beginner to Pro Best Seller 60 Lectures 5.5 hours Nicholas Lever More Detail Learn TypeORM for NestJS 19 Lectures 50 mins James Coonce More Detail Print Page Previous Next Advertisements ”;

Node.js – MongoDB Limit

Node.js – MongoDB Limit ”; Previous Next The Limit() method in MongoDB has a similar effect as in Limit clause in SQL. It restricts the number of documents returned by find() query to a specified number. The limit() method takes a single integer as argument. It the argument is omitted, it implies that no limit has been applied. To understand how the limit() function works, we shall use the orders collection in our database. Out of the available documents, those with price greater than or equal to 10 can be retrieved by the following code − Example const {MongoClient} = require(”mongodb”); async function main(){ const uri = “mongodb://localhost:27017/”; const client = new MongoClient(uri); try { await client.connect(); await limitdocs(client, “mydb”, “orders”); } finally { await client.close(); } } main().catch(console.error); async function limitdocs(client, dbname, colname){ var myqry = {numPurchased:{$gte:10}}; const result = await client.db(dbname).collection(colname).find({“numPurchased”:{$gte:10}}).toArray(); console.log(JSON.stringify(result)); } Output [{“_id”:”658d7f3b30a92c8e5018a43a”,”orderId”:201,”custid”:301,”prodId”:100,”numPurchased”:20},{“_id”:”658d7f3b30a92c8e5018a43b”,”orderId”:202,”custid”:302,”prodId”:101,”numPurchased”:10},{“_id”:”658d7f3b30a92c8e5018a43d”,”orderId”:204,”custid”:303,”prodId”:103,”numPurchased”:15},{“_id”:”658d7f3b30a92c8e5018a43e”,”orderId”:205,”custid”:303,”prodId”:103,”numPurchased”:20},{“_id”:”658d7f3b30a92c8e5018a441″,”orderId”:208,”custid”:301,”prodId”:100,”numPurchased”:10},{“_id”:”658d7f3b30a92c8e5018a442″,”orderId”:209,”custid”:303,”prodId”:103,”numPurchased”:30}] Now we will apply a limit to the result returned by find() query to 1. The syntax of limit() method is as follows − collection.find(query).limit(number); Change the limitdocs() function to the following code, to obtain number of documents limited to the specified number. async function limitdocs(client, dbname, colname){ var myqry = {numPurchased:{$gte:10}}; const result = await client.db(dbname).collection(colname).find({“numPurchased”:{$gte:10}}).limit(1).toArray(); console.log(JSON.stringify(result)); } Output [{“_id”:”658d7f3b30a92c8e5018a43a”,”orderId”:201,”custid”:301,”prodId”:100,”numPurchased”:20}] The find() query fetches the documents tht atisfy the filter condition, starting from its first occurrence. If you want to skip certain number of documents, use the skip() clause. collection.find(query).limit(x).skip(y) Out of the documents returned by find(), only x documents will populate the resultset, out of which first y documents will be removed. The following limitdocs() function return the second document in orders collection that has price>=10 async function limitdocs(client, dbname, colname){ var myqry = {numPurchased:{$gte:10}}; const result = await client.db(dbname).collection(colname).find({“numPurchased”:{$gte:10}}).limit(1).skip(1).toArray(); console.log(JSON.stringify(result)); } Output [{“_id”:”658d7f3b30a92c8e5018a43b”,”orderId”:202,”custid”:302,”prodId”:101,”numPurchased”:10}] Print Page Previous Next Advertisements ”;

Node.js – MongoDB Query

Node.js – MongoDB Query ”; Previous Next The find() and findOne() methods defined in mongodb driver module for Node.js returns all documents or the first document from the specified collection that satisfy the query argument. You can use logical operators to construct a filter in the query object as follows − MongoDB Operators MongoDB doesn”t use traditional logical operator symbols. Instead, it has its own operators as listed below − Sr.No MongoDB Operator & Description 1 $eq equal to (==) 2 $gt greater than (>) 3 $gte greater than or equal to (>=) 4 $in if equal to any value in array 5 $lt less than (<) 6 $lte less than or equal to (<=) 7 $ne not equal to (!=) 8 $nin if not equal to any value in array The operators are used in find() method to apply filter. Following statement returns products with price>10000 Example const {MongoClient} = require(”mongodb”); async function main(){ const uri = “mongodb://localhost:27017/”; const client = new MongoClient(uri); try { // Connect to the MongoDB cluster await client.connect(); // Make the appropriate DB calls // Create a single new listing await fetchdocs(client, “mydb”, “products”); } finally { // Close the connection to the MongoDB cluster await client.close(); } } main().catch(console.error); async function fetchdocs(client, dbname, colname){ const result = await client.db(dbname).collection(colname).find({“price”:{$gt:10000}}).toArray(); console.log(JSON.stringify(result)); } Output [{“_id”:”6580964f20f979d2e9a72ae7″,”ProductID”:1,”Name”:”Laptop”,”price”:25000},{“_id”:”6580964f20f979d2e9a72ae8″,”ProductID”:2,”Name”:”TV”,”price”:40000}] The $and as well as $or operators are available for compound logical expressions. Their usage is as follows − db.collection.find($and:[{“key1″:”value1”}, {“key2″:”value2”}]) Use following command to fetch products with price between 1000 and 10000. async function fetchdocs(client, dbname, colname){ const result = await client.db(dbname).collection(colname).find({$and:[{“price”:{$gt:1000}}, {“price”:{$lt:10000}}]}).toArray(); console.log(JSON.stringify(result)); } Output [{“_id”:”6580964f20f979d2e9a72ae9″,”ProductID”:3,”Name”:”Router”,”price”:2000},{“_id”:”6580964f20f979d2e9a72aea”,”ProductID”:4,”Name”:”Scanner”,”price”:5000},{“_id”:”6580964f20f979d2e9a72aeb”,”ProductID”:5,”Name”:”Printer”,”price”:9000}] Regex You can also create the filter by forming regex expressions. The $regex variable is used as the key in the query JSON representation. The following code returns all the products whose name starts with P. Example async function fetchdocs(client, dbname, colname){ const result = await client.db(dbname).collection(colname).find({Name:{$regex:”^P”}}).toArray(); console.log(JSON.stringify(result)); } Output [{“_id”:”6580964f20f979d2e9a72aeb”,”ProductID”:5,”Name”:”Printer”,”price”:9000}] In the following example, the resultset contains the documents with name starting with Ro. async function fetchdocs(client, dbname, colname){ const result = await client.db(dbname).collection(colname).find({Name: /Ro/}).toArray(); console.log(JSON.stringify(result)); } Output [{“_id”:”6580964f20f979d2e9a72ae9″,”ProductID”:3,”Name”:”Router”,”price”:2000}] To obtain the products with names ending with er, use the $ symbol at the end. async function fetchdocs(client, dbname, colname){ const result = await client.db(dbname).collection(colname).find({Name: /er$/}).toArray(); console.log(JSON.stringify(result)); } Output [{“_id”:”6580964f20f979d2e9a72ae9″,”ProductID”:3,”Name”:”Router”,”price”:2000},{“_id”:”6580964f20f979d2e9a72aea”,”ProductID”:4,”Name”:”Scanner”,”price”:5000},{“_id”:”6580964f20f979d2e9a72aeb”,”ProductID”:5,”Name”:”Printer”,”price”:9000}] Print Page Previous Next Advertisements ”;

Node.js – Built-in Modules

Node.js – Built-in Modules ”; Previous Next A module in Node.js is a collection of independent and reusable code that can be imported into any Node.js application. The Node.js runtime software comes with the V8 JavaScript engine, bundled with a number of core modules, that perform important server-side tasks, such as managing event loop, perform file IO and operating system-specific functions etc. Example The following code snippet returns a list of all the built-in modules − const builtinModules = require(”repl”)._builtinLibs; console.log(builtinModules); Output [ ”assert”, ”assert/strict”, ”async_hooks”, ”buffer”, ”child_process”, ”cluster”, ”console”, ”constants”, ”crypto”, ”dgram”, ”diagnostics_channel”, ”dns”, ”dns/promises”, ”domain”, ”events”, ”fs”, ”fs/promises”, ”http”, ”http2”, ”https”, ”inspector”, ”inspector/promises”, ”module”, ”net”, ”os”, ”path”, ”path/posix”, ”path/win32”, ”perf_hooks”, ”process”, ”punycode”, ”querystring”, ”readline”, ”readline/promises”, ”repl”, ”stream”, ”stream/consumers”, ”stream/promises”, ”stream/web”, ”string_decoder”, ”sys”, ”timers”, ”timers/promises”, ”tls”, ”trace_events”, ”tty”, ”url”, ”util”, ”util/types”, ”v8”, ”vm”, ”wasi”, ”worker_threads”, ”zlib” ] Node.js has many core modules that provide essential functionalities for building applications. Here”s a list of some of the most important core modules − Sr.No Core Modules & Description 1 assert Provides a set of assertion functions for verifying invariants. 2 buffer A Buffer objects represent fixed-legth of sequence of bytes. 3 http Provides an interface for creating HTTP servers and making HTTP requests. 4 fs Provides functions for working with files and directories. 5 path Provides functions for working with file paths. 6 url Provides functions for parsing and building URLs. 7 util Provides utility functions for working with data and strings. 8 crypto Provides functions for cryptography and secure hashing. 9 process Provides information about the current Node.js process and allows you to interact with the operating system. 10 net Provides low-level networking functionality. 11 stream Provides a basic framework for working with streams of data. 12 events Provides an event emitter class for custom event handling. 13 console Provides functions for writing to the console. 14 readline Provides functions for reading line-by-line from a stream. 15 query String Provides utilities for parsing and formatting URL query strings. 16 v8 Provides functions that are specific to the version of v8. 17 os Provides functions and properties related. Print Page Previous Next Advertisements ”;

Node.js – MongoDB Delete

Node.js – MongoDB Delete ”; Previous Next The mongodb driver for Node.js includes two methods in the Collection class. The deleteOne() method deletes one document, whereas the deleteMany() method is used to delete more than on documents at a time. Both the methods need a filter argument. collection.deleteOne(filter); Note that if there are more than one documents that satisfy the given filter condition, only the first document is deleted. deleteOne() In the following example. The deleteOne() method removes a document from products collection, whose name field matches TV. const {MongoClient} = require(”mongodb”); async function main(){ const uri = “mongodb://localhost:27017/”; const client = new MongoClient(uri); try { await client.connect(); await deldocs(client, “mydb”, “products”); } finally { await client.close(); } } main().catch(console.error); async function deldocs(client, dbname, colname){ var myqry = { Name: “TV” }; const result = await client.db(dbname).collection(colname).deleteOne(myqry); console.log(“Document Deleted”); } Use MongoCompass (or MongoShell) to verify if the expected document has been removed after the above code is executed. deleteMany() The deleteMany() method also use the filter argument. However, it causes all the document satisfying the specified condition will be removed. In the code above, change the deldocs() function as follows. It results in all the documents with price>10000 to be removed. async function deldocs(client, dbname, colname){ var myqry = {“price”:{$gt:10000}}; const result = await client.db(dbname).collection(colname).deleteMany(myqry); console.log(“Documents Deleted”); } Drop Collection You can remove a collection from the database with drop() method. Example const {MongoClient} = require(”mongodb”); async function main(){ const uri = “mongodb://localhost:27017/”; const client = new MongoClient(uri); try { await client.connect(); await dropcol(client, “mydb”, “products”); } finally { await client.close(); } } main().catch(console.error); async function dropcol(client, dbname, colname){ const result = await client.db(dbname).collection(colname).drop(); console.log(“Collection dropped “); } There is also a dropCollection() method available with the db object. const {MongoClient} = require(”mongodb”); async function main(){ const uri = “mongodb://localhost:27017/”; const client = new MongoClient(uri); try { await client.connect(); await dropcol(client, “mydb”, “orders”); } finally { await client.close(); } } main().catch(console.error); async function dropcol(client, dbname, colname){ const result = await client.db(dbname).dropCollection(colname); console.log(“Collection dropped”); } Print Page Previous Next Advertisements ”;

Node.js – Quick Guide

Node.js – Quick Guide ”; Previous Next Node.js – Introduction What is Node.js? Node.js is a server-side platform built on Google Chrome”s JavaScript Engine (V8 Engine). Node.js was developed by Ryan Dahl in 2009 and its latest version is v0.10.36. The definition of Node.js as supplied by its official documentation is as follows − Node.js is a platform built on Chrome”s JavaScript runtime for easily building fast and scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices. Node.js is an open source, cross-platform runtime environment for developing server-side and networking applications. Node.js applications are written in JavaScript, and can be run within the Node.js runtime on OS X, Microsoft Windows, and Linux. Node.js also provides a rich library of various JavaScript modules which simplifies the development of web applications using Node.js to a great extent. Node.js = Runtime Environment + JavaScript Library Features of Node.js Following are some of the important features that make Node.js the first choice of software architects. Asynchronous and Event Driven − All APIs of Node.js library are asynchronous, that is, non-blocking. It essentially means a Node.js based server never waits for an API to return data. The server moves to the next API after calling it and a notification mechanism of Events of Node.js helps the server to get a response from the previous API call. Very Fast − Being built on Google Chrome”s V8 JavaScript Engine, Node.js library is very fast in code execution. Single Threaded but Highly Scalable − Node.js uses a single threaded model with event looping. Event mechanism helps the server to respond in a non-blocking way and makes the server highly scalable as opposed to traditional servers which create limited threads to handle requests. Node.js uses a single threaded program and the same program can provide service to a much larger number of requests than traditional servers like Apache HTTP Server. No Buffering − Node.js applications never buffer any data. These applications simply output the data in chunks. License − Node.js is released under the MIT license. Who Uses Node.js? Following is the link on github wiki containing an exhaustive list of projects, application and companies which are using Node.js. This list includes eBay, General Electric, GoDaddy, Microsoft, PayPal, Uber, Wikipins, Yahoo!, and Yammer to name a few. Projects, Applications, and Companies Using Node Concepts The following diagram depicts some important parts of Node.js which we will discuss in detail in the subsequent chapters. Where to Use Node.js? Following are the areas where Node.js is proving itself as a perfect technology partner. I/O bound Applications Data Streaming Applications Data Intensive Real-time Applications (DIRT) JSON APIs based Applications Single Page Applications Where Not to Use Node.js? It is not advisable to use Node.js for CPU intensive applications. Node.js – Environment Setup Try it Option Online You really do not need to set up your own environment to start learning Node.js. Reason is very simple, we already have set up Node.js environment online, so that you can execute all the available examples online and learn through practice. Feel free to modify any example and check the results with different options. Try the following example using the Live Demo option available at the top right corner of the below sample code box (on our website) − Live Demo /* Hello World! program in Node.js */ console.log(“Hello World!”); For most of the examples given in this tutorial, you will find a Try it option, so just make use of it and enjoy your learning. Local Environment Setup If you are still willing to set up your environment for Node.js, you need the following two softwares available on your computer, (a) Text Editor and (b) The Node.js binary installables. Text Editor This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi. Name and version of text editor can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on windows as well as Linux or UNIX. The files you create with your editor are called source files and contain program source code. The source files for Node.js programs are typically named with the extension “.js“. Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, and finally execute it. The Node.js Runtime The source code written in source file is simply javascript. The Node.js interpreter will be used to interpret and execute your javascript code. Node.js distribution comes as a binary installable for SunOS , Linux, Mac OS X, and Windows operating systems with the 32-bit (386) and 64-bit (amd64) x86 processor architectures. Following section guides you on how to install Node.js binary distribution on various OS. Download Node.js archive Download latest version of Node.js installable archive file from Node.js Downloads. At the time of writing this tutorial, following are the versions available on different OS. OS Archive name Windows node-v6.3.1-x64.msi Linux node-v6.3.1-linux-x86.tar.gz Mac node-v6.3.1-darwin-x86.tar.gz SunOS node-v6.3.1-sunos-x86.tar.gz Installation on UNIX/Linux/Mac OS X, and SunOS Based on your OS architecture, download and extract the archive node-v6.3.1-osname.tar.gz into /tmp, and then finally move extracted files into /usr/local/nodejs directory. For example: $ cd /tmp $ wget http://nodejs.org/dist/v6.3.1/node-v6.3.1-linux-x64.tar.gz $ tar xvfz node-v6.3.1-linux-x64.tar.gz $ mkdir -p /usr/local/nodejs $ mv node-v6.3.1-linux-x64/* /usr/local/nodejs Add /usr/local/nodejs/bin to the PATH environment variable. OS Output Linux export PATH=$PATH:/usr/local/nodejs/bin Mac export PATH=$PATH:/usr/local/nodejs/bin FreeBSD export PATH=$PATH:/usr/local/nodejs/bin Installation on Windows Use the MSI file and follow the prompts to install the Node.js. By default, the installer uses the Node.js distribution in C:Program Filesnodejs. The installer should set the C:Program Filesnodejsbin directory in window”s PATH environment variable. Restart any open command prompts for the change to take effect. Verify installation: Executing a File Create a js file named main.js on your machine (Windows or Linux)

Node.js – Utility Modules

Node.js – Utility Modules ”; Previous Next There are several utility modules available in Node.js module library. These modules are very common and are frequently used while developing any Node based application. Sr.No. Module Name & Description 1 OS Module Provides basic operating-system related utility functions. 2 Path Module Provides utilities for handling and transforming file paths. 3 Net Module Provides both servers and clients as streams. Acts as a network wrapper. 4 DNS Module Provides functions to do actual DNS lookup as well as to use underlying operating system name resolution functionalities. 5 Domain Module Provides ways to handle multiple different I/O operations as a single group. Print Page Previous Next Advertisements ”;

Node.js – MongoDB Update

Node.js – MongoDB Update ”; Previous Next The Update operation refers to modifying the value of one or more fields in a document in a MongoDB collection. The mongodb driver for Node.js defines updateOne() and updateMany() methods. The updateOne() method is used to modify a single document, whereas the updateMany() method performs updating on more than one documents. The updateOne() method has the following syntax − collection.updateOne(query, values); The query parameter helps in finding the desired document to be updated. The values parameter contains the key:value pairs with which the document is to be modified. The updateMany() method follows the same syntax, except that the query returns multiple documents from the collection. updateOne() The following example changes price of a document with ProductID=3. The $set operator assigns a new value to the price field. const {MongoClient} = require(”mongodb”); async function main(){ const uri = “mongodb://localhost:27017/”; const client = new MongoClient(uri); try { await client.connect(); await sortdocs(client, “mydb”, “products”); } finally { // Close the connection to the MongoDB cluster await client.close(); } } main().catch(console.error); async function sortdocs(client, dbname, colname){ var qry = { ProductID: 3 }; var vals = { $set: { Name: “Router”, price: 2750 } }; const result = await client.db(dbname).collection(colname).updateOne(qry, vals); console.log(“Document updated”); } To verify that the document has been updated, use the Mongosh shell and enter the commands as below − > use mydb < switched to db mydb > db.products.find({“ProductID”:3}) { _id: ObjectId(“6580964f20f979d2e9a72ae9″), ProductID: 3, Name: ”Router”, price: 2750 } updateMany() Assuming that the products collection has the following documents that have the name ending with ”er”. The following sortdocs() function increments the price of all the above products by Rs. 125. We have used the $inc operator. Example async function sortdocs(client, dbname, colname){ var qry = {Name: /er$/}; var vals = { $inc: { price: 125 } }; const result = await client.db(dbname).collection(colname).updateMany(qry, vals); console.log(“Documents updated”); } Output Print Page Previous Next Advertisements ”;