Mostly all modern-day web applications have some sort of data storage system at the backend. For example, if you take the case of a web shopping application, data such as the price of an item would be stored in the database.
The Node js framework can work with databases with both relational (such as Oracle and MS SQL Server) and non-relational databases (such as MongoDB).
MongoDB is a cross-platform (runs on multiple operating systems), document-oriented database management system (DBMS). MongoDB is also a NoSQL database, which means it does not use SQL to perform operations on a database.
MongoDB uses documents that are in JSON-like format, known as BSON, which is the binary encoding of JSON.
It’s developed as an open-source project by MongoDB Inc. under the Server Side Public License.
Node and MongoDB work very-well together, in part because Mongo uses a JavaScript engine built into the database since JavaScript is good at handling JSON objects.
Compared to other databases, such as MySQL, MongoDB is fast for storing certain types of data and can be automatically scaled. It’s very simple to implement and get running.
With Mongo being a NoSQL database, it has its own way of storing data. Here are some of the constructs that make up the database structure:
npm install mondodb --save
Step 1 – Create a database
const { MongoClient } = require("mongodb");
const uri = "mongodb://127.0.0.1:27017/";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
async function run() {
try {
const database = client.db('navigcollection');
console.log("Database Created !!!")
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
Now run this file :
node createDatabase.js
Step 2 – Create collection in database – Create a .js file createcollection.js and write this code.
const { MongoClient } = require("mongodb"); // Replace the uri string with your connection string. const uri = "mongodb://127.0.0.1:27017/"; const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); async function run() { try { const database = client.db('navigcollection'); await database.createCollection("pract3", function (error, response) { if (error) { throw error; } }); console.log("collection is created.....") } finally { // Ensures that the client will close when you finish/error await client.close(); } } run().catch(console.dir);
Now run this :
node createcollection.js
After running, the output will look like:
Step 3 – Insert record in database – Now insert a record in the collection, to insert a record in the database create a new file insert1docu.js and write this code.
const { MongoClient } = require("mongodb");
// Replace the uri string with your connection string.
const uri = "mongodb://127.0.0.1:27017/";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
async function run() {
try {
var nodetestDB = client.db("navigcollection"); //here
var customersCollection = nodetestDB.collection("pract");
var customer = { _id: 111, name: "Santosh Kumar", address: "B-222, Sector-19, NOIDA", orderdata: "Arrow Shirt" };
await customersCollection.insertOne(customer, function (error, response) {
if (error) { throw error; }
});
console.log("1 document inserted");
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
Now run this program :
node insert1docu.js
Output will look like:
Step 3 – Insert Many records : create a js file createmanydocu.js and write this code:
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/';
MongoClient.connect(url, function(error, databases) {
if (error) {
const { MongoClient } = require("mongodb");
// Replace the uri string with your connection string.
const uri = "mongodb://127.0.0.1:27017/";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
async function run() {
try {
var nodetestDB = client.db("navigcollection"); //here
var pract = [
{ _id: 11, name: "Chaman Gautam", address: "Harvansh nagar Ghaziabad", orderdata: "Jeans" },
{ _id: 12, name: "Shivani", address: "Harvansh nagar Ghaziabad", orderdata: "Jeans" },
{ _id: 13, name: "Menu", address: "Harvansh nagar Ghaziabad", orderdata: "Top" },
{ _id: 14, name: "Brajbala", address: "Harvansh nagar Ghaziabad", orderdata: "Dinig table" },
{ _id: 15, name: "Ramsaran", address: "Harvansh nagar Ghaziabad", orderdata: "Washing machine" },
{ _id: 16, name: "Dheeraj", address: "Harvansh nagar Ghaziabad", orderdata: "Jeans" }
]
var customersCollection = nodetestDB.collection("pract");
await customersCollection.insertMany(pract, function (error, response) {
if (error) { throw error; }
});
console.log("Many document inserted");
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
Now run this file :
node createmanydocu.js
Step 5 – Find record from database – Find 1 record from collection
const { MongoClient } = require("mongodb");
// Replace the uri string with your connection string.
const uri = "mongodb://127.0.0.1:27017/";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
async function run() {
try {
var nodetestDB = client.db("navigcollection"); //here
var customersCollection = nodetestDB.collection("pract");
const result = await customersCollection.findOne({ name: 'Shivani' }, function(err) {
if (err) throw err;
})
console.log("one record is find now....." + result.name + ", " + result.address + ", " + result.orderdata);
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
Now run this :
node find1docu.js
Output will look like this:
const { MongoClient } = require("mongodb"); // Replace the uri string with your connection string. const uri = "mongodb://127.0.0.1:27017/"; const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); async function run() { try { var nodetestDB = client.db("navigcollection"); //here var customersCollection = nodetestDB.collection("pract"); const result = await customersCollection.find({}).toArray(function (err) { if (err) throw err; }) for (i = 0; i < result.length; i++) { let pract = result[i]; console.log(pract.name + ", " + pract.address + ", " + pract.orderdata); } } finally { // Ensures that the client will close when you finish/error await client.close(); } } run().catch(console.dir);
Now compile this program in terminal and write command for the compile:
node findmanydocu.js
After running, the output will look like,
Step 6 – update record in collection
const { MongoClient } = require("mongodb");
// Replace the uri string with your connection string.
const uri = "mongodb://127.0.0.1:27017/";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
async function run() {
try {
var nodetestDB = client.db("navigcollection"); //here
var customersCollection = nodetestDB.collection("pract");
var whereClause = { name: /Chaman Gautam/ };
var newvalues = { $set: { name: "Lucky Gautam" } };
const result = await customersCollection.updateOne(whereClause,newvalues, function(err) {
if (err) throw err;
})
console.log("document updated");
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
Now compile this program in terminal and write the command for compile:
node updateone.js
const { MongoClient } = require("mongodb");
// Replace the uri string with your connection string.
const uri = "mongodb://127.0.0.1:27017/";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
async function run() {
try {
var nodetestDB = client.db("navigcollection"); //here
var customersCollection = nodetestDB.collection("pract");
var whereClause = { address: /Harvansh nagar/ };
var newvalues = { $set: { name: "Shivani" } };
const result = await customersCollection.updateMany(whereClause,newvalues, function(err) {
if (err) throw err;
})
console.log("Multiple Documents updated");
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
Now you need to compile this file in terminal using command
node updatemany.js
After running this command output will be shown in the terminal like this
Step 7 – now delete operation
const { MongoClient } = require("mongodb");
// Replace the uri string with your connection string.
const uri = "mongodb://127.0.0.1:27017/";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
async function run() {
try {
var nodetestDB = client.db("navigcollection"); //here
var customersCollection = nodetestDB.collection("pract");
var deleteQuery = { name: 'Shivani' };
const result = await customersCollection.deleteOne(deleteQuery, function(err) {
if (err) throw err;
})
console.log("1 document deleted");
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
Now compile this program in terminal and write command for compile,
node deleteone.js
After compiling, the code output will be shown in the terminal like this:
const { MongoClient } = require("mongodb");
// Replace the uri string with your connection string.
const uri = "mongodb://127.0.0.1:27017/";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
async function run() {
try {
var nodetestDB = client.db("navigcollection"); //here
var customersCollection = nodetestDB.collection("pract");
var deleteQuery = { name: 'Shivani' };
const result = await customersCollection.deleteMany(deleteQuery, function(err) {
if (err) throw err;
})
console.log("Many documents deleted");
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
Now you need to compile this code in terminal using command
node deletemany.js