Contents hide 1) Setup npm 2) Database And Table Creation 3) Creating Table 4) Inserting And Viewing Data 5) Viewing Single Data 6) Viewing All Data 7) Filter The Result 8) Sorting The Result 9) Updating The Result 10) Updating Only Specific Fields 11) Updating Multiple Documents 12) Deleting The Data 13) Dropping The Collection Beginning With NodeJS And MongoDB Queries, In this tutorial, we will see the different MongoDB queries (i.e insert, update, delete, drop, create etc) applying through nodeJS. Topics : Setup npm Database And Table Creation Inserting And Viewing Data Filter The Result Updating The Result Deleting The Data Setup npm Let’s create a directory with any name to create the app through the terminal. $ mkdir node_mongo_demo After creating directory lets begin with npm setup for the package.json file. So enter the details for file creation. $ npm init // filing up the procedure name: (node_mongo_demo) //default folder name version: (1.0.0) 0.0.1 // your version number description: Tutorial on Nodejs With mongoDB Queries entry point: (index.js) app.js // your main file test command: git repository: // git project if any keywords: geekstrick author: rehmaanali license: (ISC) As it created the package.json file. So now we just need to install the MongoDB package by just a single command in terminal. $ npm install mongodb --save The command will install the MongoDB node Package as well as it will make changes in the package.json file. Here it shows the dependencies and its version number. { "name": "node_sql_demo", "version": "0.0.1", "description": "Tutorial On NodeJS with MongoDB Queries", "main": "app.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [ "geekstrick" ], "author": "RehmaanAli", "license": "ISC", "dependencies": { "mongodb": "^2.2.28" } } Database And Table Creation First import the MongoDB package in the app file by the require method and also start the MongoDB mongodb://localhost:27017 server. As we declare the main as app.js so the file must be named as that only. And Now will create the database as well a table in that particular Database. But first, we will create the database var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/demo"; // Creating database named as 'Demo' MongoClient.connect(url, function(err, db) { if (err) throw err; console.log("Database created!"); db.close(); }); Now to run the app.js file simply write the command $ node app.js Database created! // Successfully connected message Creating Table To create a table in MongoDB, we will use the createCollection() method var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/demo"; MongoClient.connect(url, function(err, db) { if (err) throw err; db.createCollection("books", function(err, res) { if (err) throw err; console.log("Table created!"); db.close(); }); }); Every time if you want to run the app.js file just write the similar command $ node app.js Table created! // Successfully connected message Inserting And Viewing Data Let us see the further procedure for inserting data and viewing in the terminal. So first we have to insert data into the table. To insert a record into a table in MongoDB, we will use the insertOne() method. The first parameter of the insertOne() method is an object containing the name and value pair of each field in the record you want to insert. As MongoDB stores the data in JSON format. It also takes a callback function where you can work with any errors or the result of the insertion: var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/demo"; //database MongoClient.connect(url, function(err, db) { if (err) throw err; // insert record in JSON format var myobj = { id:0001, name: "Sherlock Cases", author: "MR.Sherlock" }; db.collection("books").insertOne(myobj, function(err, res) { if (err) throw err; console.log("1 record inserted"); db.close(); }); }); This will insert the given JSON record in the assigned database and its table. Even you can insert multiple data at once.using insert() method. var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/demo"; MongoClient.connect(url, function(err, db) { if (err) throw err; var myobj = [ { id:0001, name: "Sherlock Cases", author: "MR.Sherlock"}, { id:0002, name: "Comedy Man", author: "MR.bean"} ]; db.collection("customers").insert(myobj, function(err, res) { if (err) throw err; console.log("Number of records inserted: " + res.insertedCount); db.close(); }); }); Viewing Single Data To select data from a table in MongoDB, we can use the findOne() method. The findOne() method returns the first occurrence in the selection. The first parameter of the findOne() method is a query object. In this example, we use an empty query object, which selects all records in a table (but returns only the first record). var http = require('http'); var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/demo"; MongoClient.connect(url, function(err, db) { if (err) throw err; db.collection("books").findOne({}, function(err, result) { if (err) throw err; console.log(result.name); db.close(); }); }); And Now Running the app.js file for the single output $ node app.js Sherlock Cases Viewing All Data To select data from a table in MongoDB, we can also use the find() method. The find() method returns all occurrences in the selection. The first parameter of the find() method is a query object. In this example, we use an empty query object, which selects all records in a table. var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/demo"; MongoClient.connect(url, function(err, db) { if (err) throw err; db.collection("books").find({}).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); }); }); And the output is in JSON format. Every time you insert the data in a table it automatically generates the unique for a single collection. [ { _id: 593823c626751300c89d25f9, id: 1, name: 'Sherlock Cases', author: 'MR.Sherlock' }, { _id: 59382b9c0e9afd1a30838cf7, id: 2, name: 'Comedy Man', author: 'MR.bean' } ] Filter The Result In this section, we will see the ‘sort’ and ‘Query’. let’s start with Query When selecting records from a table, you can filter the result by using a query object. The first argument of the find() method is a query object and is used to limit the search. Selecting record with author = MR.Bean var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/demo"; MongoClient.connect(url, function(err, db) { if (err) throw err; var query = { id: 2 }; db.collection("books").find(query).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); }); }); And the output will be: [ { _id: 59382b9c0e9afd1a30838cf7, id: 2, name: 'Comedy Man', author: 'MR.bean' } ] Sorting The Result Use the sort() method to sort the result in ascending or descending order. The sort() method takes one parameter, an object defining the sorting order. var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/demo"; MongoClient.connect(url, function(err, db) { if (err) throw err; var mysort = { name: 1 }; // sort name by ascending order db.collection("books").find().sort(mysort).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); }); }); { name: 1 } // ascending { name: -1 } // descending And this will give you the sorted result as: [ { _id: 59382b9c0e9afd1a30838cf7, id: 2, name: 'Comedy Man', author: 'MR.bean' }, { _id: 593823c626751300c89d25f9, id: 1, name: 'Sherlock Cases', author: 'MR.Sherlock' } ] Updating The Result we can update records, or documents in MongoDB, by using the update() method. By default, the update() method only updates one document. The first parameter of the update() method is a query object defining which document to update. We will have to set the every field, if you left any field empty it will update and set the field empty. you don’t have to set the default _id field it won’t changes. But in our collection, we have our separate id which we have to mention it while updating. var MongoClient = require('mongodb').MongoClient; var url = "mongodb://127.0.0.1:27017/demo"; MongoClient.connect(url, function(err, db) { if (err) throw err; var myquery = { author: "MR.bean" }; var new_values = { id: 0002, name: "Comedy Man", author: "MR.charlie" }; db.collection("books").update(myquery, new_values, function(err, res) { if (err) throw err; console.log(res.result.nModified + " record updated"); db.close(); }); }); Updating Only Specific Fields To update only selected fields, we will use the $set operator to prevent fields from being left empty. ... var myquery = { author: "MR.bean" }; var new_values = { $set: { author: "MR.Charlie" } }; db.collection("books").update(myquery, new_values, function(err, res) { ... Updating Multiple Documents To update all documents, you must set the multi-option to true. The third parameter of the update() method is an object of options, one of these options is the multi-option: var MongoClient = require('mongodb').MongoClient; var url = "mongodb://127.0.0.1:27017/demo"; MongoClient.connect(url, function(err, db) { if (err) throw err; var myquery = { author: /^M/ }; var newvalues = {$set: {author: "Anyone"} }; var myoptions = { multi: true }; db.collection("books").update(myquery, newvalues, myoptions, function(err, res) { if (err) throw err; console.log(res.result.nModified + " record(s) updated"); db.close(); }); }); Deleting The Data In this section, we will see the removing of the data from the collection and dropping down the full collection. Let start with deleting the record. We can delete records, or documents in MongoDB, by using the remove() method. The first parameter of the remove() method is a query object defining which documents to delete. var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/demo"; MongoClient.connect(url, function(err, db) { if (err) throw err; var myquery = { id: 1 }; db.collection("books").remove(myquery, function(err, obj) { if (err) throw err; console.log(obj.result.n + " record deleted"); db.close(); }); }); Dropping The Collection We can delete a table, or collection in MongoDB, by using the drop() method. The drop() method takes a callback function containing the error object and the result parameter which returns true if the collection was dropped successfully, otherwise, it returns false. var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/demo"; MongoClient.connect(url, function(err, db) { if (err) throw err; db.collection("books").drop(function(err, delOK) { if (err) throw err; if (delOK) console.log("Table deleted"); db.close(); }); }); Share this:TwitterFacebookRedditLinkedInWhatsAppPrintTumblr Related Tags: JavaScript, MongoDB, nodejs, npm