Classified as a No SQL database , MongoDB is a scalable, open
source, high performance , document-oriented database designed
by keeping developers agility in mind. It is document-oriented
which means that it does not store data in tables and rows as we
would in relational databases like MySQL, In this we store data
in JSON-like documents with dynamic schema.
Advantages :
The first step is to establish a connection between the mongodb
database and our node.js
application.
//Including the required packages
var mongo = require('mongodb');
//Establishing the connection
var new_db = "mongodb://localhost:27017/demo_db"
connect
method.
Connect() is an inbuilt method used to is an inbuilt method used to Creates a connection
to a MongoDB instance and returns the reference to the database. It instantiates a new
connection to the MongoDB instance running on the localhost interface and returns a
reference to demo_db. Snippet for establishing connection using connect method is given
below :
//File Name is : demo-db.js
//establishing the connection
mongo.connect(new_db ,(error , db) => {
if (error){
throw error;
}
console.log("Database demo_db created successfully");
//To close the connection
db.close();
});
> node demo-db.js
Database demo_db created successfully
//Name of the file : insert-mongo.js
mongo.connect(new_db , function(error , db){
if (error){
throw error;
}
var data = { name : "rishabhio" , age : "25" , mobile : "1234567890" }
db.collection("details").insertOne(data, (err , collection) => {
if(err) throw err;
console.log("Record inserted successfully");
console.log(collection);
});
});
> node insert-mongo.js
>node insert_mongo_nodejs.js
Record inserted successfully
{ result: { ok: 1, n: 1 },
connection: null,
message: undefined,
ops:
[ { name: 'rishabhio',
age: '25',
mobile: '1234567890',
_id: 597073b2c6f60f5b3c23a1a5 } ],
insertedCount: 1,
insertedId: 597073b2c6f60f5b3c23a1a5
}
//name of the file : read-one.js
mongo.connect(new_db , function(error , db){
if (error){
throw error;
}
//findOne() reads the first occurance of any data from the database.
db.collection("details").findOne({}, (err , collection) => {
if(err) throw err;
console.log("Record Read successfully");
console.log(collection);
db.close();
});
});
> node read-one.js
Record Read successfully
{ name: 'Nodejsera',
age: '23',
mobile: '9876543210',
_id: 59706a56a4f6761e3cc22c98 }
//name of the file : read-all.js
mongo.connect(new_db , function(error , db){
if (error){
throw error;
}
//Read All the data from the "details" collection.
db.collection("details").find({}).toArray( (err , collection) => {
if(err) throw err;
console.log("Record Read successfully");
console.log(collection);
db.close();
});
});
> node read-all.js
Record Read successfully
[ { name: 'Nodejsera',
age: '23',
mobile: '9876543210',
_id: 59706a56a4f6761e3cc22c98 },
{ name: 'rishabhio',
age: '25',
mobile: '1234567890',
_id: 59706c3771da112bd8b922dc },
{ name: 'rishabhio',
age: '25',
mobile: '1234567890',
_id: 597073b2c6f60f5b3c23a1a5 } ]
//name of the file : update-one.js
mongo.connect(new_db ,(error , db) => {
if (error){
throw error;
}
//Query parameter is used to search the collection.
var query = { name : "rishabhio" };
//And When the query matches the data in the DB , "data" parameter is used to update the value.
var data = { name : "nodejsera.com" , mobile : "1234567890" }
//Accessing the collection using nodejs
db.collection("details").updateOne(query , data, (err , collection) => {
if(err) throw err;
console.log("Record updated successfully");
console.log(collection);
});
});
> node update-one.js
Record updated successfully
{ result: { ok: 1, n: 1, nModified: 1 },
connection: null,
message: undefined,
modifiedCount: 1,
upsertedId: null,
upsertedCount: 0,
matchedCount: 1 }
//name of the file : update-all.js
mongo.connect(new_db ,(error , db) => {
if (error){
throw error;
}
//query store the search condition
var query = { age : {$gt : "22" } };
//data stores the updated value
var data = { $set : {age : "above 22" } }
//CREATING A COLLECTION IN MONGODB USING NODE.JS
db.collection("details").updateMany(query , data, (err , collection) => {
if(err) throw err;
console.log(collection.result.nModified + " Record(s) updated successfully"); //It will console the number of rows updated
console.log(collection);
db.close();
});
});
> node update-all.js
node updateMany-mongodb-nodejs.js
3 Record(s) updated successfully
{ result:
{
ok: 1,
n: 3,
nModified: 3
},
connection: null,
message: undefined,
modifiedCount: 3,
upsertedId: null,
upsertedCount: 0,
matchedCount: 3
}
//name of the file : delete-one.js
mongo.connect(new_db ,(error , db) => {
if (error){
throw error;
}
//query stores the search condition
var query = { age : "above 22" };
//Accessing a COLLECTION IN MONGODB USING NODE.JS
db.collection("details").deleteOne(query , (err , collection) => {
if(err) throw err;
console.log(collection.result.n + " Record(s) deleted successfully");
console.log(collection);
db.close();
});
});
> node delete-one.js
1 Record(s) deleted successfully
{
result:
{
ok: 1,
n: 1
},
connection: null,
message: undefined,
deletedCount: 1
}
//name of the file : delete-all.js
mongo.connect(new_db ,(error , db) => {
if (error){
throw error;
}
//Search query for deletion
var query = { age : "above 22" };
//Accessing the collection
db.collection("details").deleteMany(query , (err , collection) => {
if(err) throw err;
console.log(collection.result.n + " Record(s) deleted successfully");
console.log(collection);
db.close();
});
});
> node delete-all.js
2 Record(s) deleted successfully
{
result:
{
ok: 1,
n: 2
},
connection: null,
message: undefined,
deletedCount: 2
}
In this chapter of 30 days of node tutorial series, we learned about how we can establish a connection with a MongoDb database using node.js and perfrom the basic create, read, update and delete operations.