Node.js MongoDB Tutorial

FREE Online Courses: Transform Your Career – Enroll for Free!

In this article, we will see how we can use the mongo db database with node js. We will look at how to create a database, connect databases, create a collection and other methods with code and examples.

Install MongoDB:

To install MongoDB on your device run the below command:

Npm install mongodb.

Connecting to mongodb?

To connect with mongo db we will use the connect method.

Code for connecting to mongodb:

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/dataflair";
MongoClient.connect(url, function (err, db) {
    if (err) throw err;
});

Creating database:

To create a database, we will use a MongoClient object. We will pass a connection URL and the name of the database. If it does not exist, MongoDB will create the database, and connect to it.

Code for Creating database:

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/dataflair";
MongoClient.connect(url, function (err, db) {
    if (err) throw err;
    console.log("Database created!");
    db.close();
});

Output:

nodejs mongodb create database

Creating collection:

We will use the create collection method to create a collection.

Code for Creating collection:

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function (err, db) {
    if (err) throw err;
    var dbo = db.db("dataflair");
    dbo.createCollection("students", function (err, res) {
        if (err) throw err;
        console.log("Collection created!");
        db.close();
    });
});

Output:

nodejs mongodb create collection

Inserting into collection:

We will use the insert one method to insert into the collection.

Code for inserting:

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function (err, db) {
    if (err) throw err;
    var dbo = db.db("dataflair");
    var obj = { name: "abc", address: "India" };
    dbo.collection("students").insertOne(obj, function (err, res) {
        if (err) throw err;
        console.log("1 document inserted!");
        db.close();
    });
});

Output:

nodejs mongodb insert

MongoDB Find query:

To find a particular document in mongodb, we use the find method.

Code for find()

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
 
MongoClient.connect(url, function (err, db) {
    if (err) throw err;
    var dbo = db.db("dataflair");
 
 
    dbo.collection("students").findOne({}, function (err, res) {
        if (err) throw err;
        console.log(res);
        db.close();
    });
});

Output:

{
_id: new ObjectId(“616d7984ab589958610e0257”),
name: ‘abc’,
address: ‘India’
}

MongoDB Filter result :

We will use the find method and pass the query as the first argument to it.

Code for filtering the result:

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
 
MongoClient.connect(url, function (err, db) {
    if (err) throw err;
    var dbo = db.db("dataflair");
    var query = { address: "India" };
    dbo.collection("students").find(query).toArray(function (err, res) {
        if (err) throw err;
        console.log(res);
        db.close();
    });
});

Output

nodejs mongodb filter

MongoDB Sort Function:

To sort the data in some order, use the sort function.

Code for sorting

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
 
MongoClient.connect(url, function (err, db) {
    if (err) throw err;
    var dbo = db.db("dataflair");
    dbo.collection("students").find().sort({ name: 1 }).toArray(function (err, res) {
        if (err) throw err;
        console.log(res);
        db.close();
    });
});

Output:

[
{
_id: new ObjectId(“616d7984ab589958610e0257”),
name: ‘abc’,
address: ‘India’
},
    {
_id: new ObjectId(“616d7ac3895eb21861a35ad0”),
name: ‘xyz’,
address: ‘delhi’
}
]

MongoDB Limit Function:

To get a fixed amount of information, we limit the result by using the limit function.

Code for limit:

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
 
MongoClient.connect(url, function (err, db) {
    if (err) throw err;
    var dbo = db.db("dataflair");
    dbo.collection("students").find().limit(1).toArray(function (err, res) {
        if (err) throw err;
        console.log(res);
        db.close();
    });
});

Output:

[
{
_id: new ObjectId(“616d7984ab589958610e0257”),
name: ‘abc’,
address: ‘India’
}
]

MongoDB Deleting document:

We will use the delete one method to delete a single document. To delete multiple documents, use the delete many method.

Code for deleting documents:

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
 
MongoClient.connect(url, function (err, db) {
    if (err) throw err;
    var dbo = db.db("dataflair");
    var query = { address: "India" };
    dbo.collection("students").deleteOne(query, function (err, res) {
        if (err) throw err;
        console.log("1 item deleted");
        db.close();
    });
});

Output:

nodejs mongodb deleting document

MongoDB Join Method:

In order to join two collections, we use the join method.

Code for join

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
 
MongoClient.connect(url, function (err, db) {
    if (err) throw err;
    var dbo = db.db("dataflair");
    dbo.collection("schools").aggregate([
        {
            $lookup:
            {
                from: 'students',
                localField: '_id',
                foreignField: '_id',
                as: 'studentdetails'
            }
        }
    ]).toArray(function (err, res) {
        if (err) throw err;
        console.log(res);
        db.close();
    });
});

Output:

[
{
_id:1,
Schoolname:Abc delhi,studentdetails:
{
_id: new ObjectId(“616d7984ab589958610e0257”),
name: ‘abc’,
address: ‘India’,
}
}
]

MongoDB Dropping collection:

We will use the drop() method to delete a collection;

Code for dropping collection:

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
 
MongoClient.connect(url, function (err, db) {
    if (err) throw err;
    var dbo = db.db("dataflair");
    var query = { address: "India" };
    dbo.collection("students").drop(function (err, res) {
        if (err) throw err;
        console.log("collection deleted");
        db.close();
    });
});

Output:

nodejs mongodb drop collection

Conclusion:

We hope you were able to learn using mongodb with node js. Do check the DataFlair website for other amazing articles.

We work very hard to provide you quality material
Could you take 15 seconds and share your happy experience on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *