Nodejs connect with MongoDB

To connect with MongoDB, Firstly we have to install the MongoDB module in the Nodejs

npm install mongodb --save

Now, create a server.js file and put the below code

var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/databaseName";
// Connect to the db
MongoClient.connect(url, function (err, db) {
   
     if(err) throw err;

     console.log("Database connected");
                
});

Now check database is connected or not

node server.js

If connected then show message “Database connected” otherwise not.

insert query:
insert a document in the users collection.

let userObj={
	name:'John',
	age:35,
    email:'John@abc.com'
}
let url="mongodb://localhost:27017/databaseName";
MongoClient.connect(url, function (err, db) {
db.collection("users").insertOne(userObj, function(err, res) {
    if (err) throw err;
    console.log("1 user document is inserted");
    db.close();
  });

 });
 

// 1 user document is inserted

update query:
update the document in the users collection.

let userSetObj={
	name:'Rom';
	age:30;
}

let whereCondition={
"email":'John@abc.com'
}
let url="mongodb://localhost:27017/databaseName";
MongoClient.connect(url, function (err, db) {
 db.collection("users").updateOne(whereCondition, {$set:userSetObj}, function(err, res) {
    if (err) throw err;
    console.log("1 document is updated successfully");
    db.close();
  });
 });

delete query:
delete the document from the users collection.

let whereCondition={
"email":'John@abc.com'
}
let url="mongodb://localhost:27017/databaseName";
MongoClient.connect(url, function (err, db) {
 db.collection("users").deleteOne(whereCondition, function(err, res) {
    if (err) throw err;
    console.log("1 document is deleted successfully");
    db.close();
  });
});

select query:
get the all documents from the users collection

let url="mongodb://localhost:27017/databaseName";
MongoClient.connect(url, function (err, db) {
 db.collection("users").find().toArray(function(err, res) {
    if (err) throw err;
    console.log("All document show successfully");
    db.close();
  });
});

// show the All documents from the users collection