Debug School

rakesh kumar
rakesh kumar

Posted on

Node.js with MongoDB

Node.js MongoDB Create Database
Node.js MongoDB Create Collection
Node.js MongoDB Insert Record
Node.js MongoDB Select Record
Node.js MongoDB Filter Query
Node.js MongoDB Sorting
Node.js MongoDB Remove
Node.js MongoDB Join
Node.js MongoDB Update
Node.js MongoDB Limit
How to retrive data in node js using mongo db
How to retrive data in node js using mongo db join collection

Node.js MongoDB Create Database

To create a database in MongoDB, First create a MongoClient object and specify a connection URL with the correct ip address and the name of the database which you want to create.

Note: MongoDB will automatically create the database if it does not exist, and make a connection to it.
Example

Create a folder named "MongoDatabase" as a database. Suppose you create it on Desktop. Create a js file named "createdatabase.js" within that folder and having the following code:

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

or

Create a database called "mydb":

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  console.log("Database created!");
  db.close();
});
Enter fullscreen mode Exit fullscreen mode

Now open the command terminal and set the path where MongoDatabase exists. Now execute the following command:
Play

Node createdatabase.js  
Node.js Create database 1
Now database is created.
Enter fullscreen mode Exit fullscreen mode

Node.js MongoDB Create Collection

MongoDB is a NoSQL database so data is stored in collection instead of table. createCollection method is used to create a collection in MongoDB.

Example

Create a collection named "employees".

Create a js file named "employees.js", having the following data:

var MongoClient = require('mongodb').MongoClient;  
var url = "mongodb://localhost:27017/ MongoDatabase";  
MongoClient.connect(url, function(err, db) {  
if (err) throw err;  
db.createCollection("employees", function(err, res) {  
if (err) throw err;  
console.log("Collection is created!");  
db.close();  
});  
});
Enter fullscreen mode Exit fullscreen mode

Open the command terminal and run the following command:

Node employees.js

Image description

Node.js MongoDB Insert Record

The insertOne method is used to insert record in MongoDB's collection. The first argument of the insertOne method is an object which contains the name and value of each field in the record you want to insert.

Example

(Insert Single record)

Insert a record in "employees" collection.

Create a js file named "insert.js", having the following code:

var MongoClient = require('mongodb').MongoClient;  
var url = "mongodb://localhost:27017/ MongoDatabase";  
MongoClient.connect(url, function(err, db) {  
if (err) throw err;  
var myobj = { name: "Ajeet Kumar", age: "28", address: "Delhi" };  
db.collection("employees").insertOne(myobj, function(err, res) {  
if (err) throw err;  
console.log("1 record inserted");  
db.close();  
});  
}); 
Enter fullscreen mode Exit fullscreen mode

Open the command terminal and run the following command:

Node insert.js

Image description

Now a record is inserted in the collection.

Insert Multiple Records
You can insert multiple records in a collection by using insert() method. The insert() method uses array of objects which contain the data you want to insert.

Example

Insert multiple records in the collection named "employees".

Create a js file name insertall.js, having the following code:

var MongoClient = require('mongodb').MongoClient;  
var url = "mongodb://localhost:27017/ MongoDatabase";  
MongoClient.connect(url, function(err, db) {  
if (err) throw err;  
var myobj = [     
{ name: "Mahesh Sharma", age: "25", address: "Ghaziabad"},  
{ name: "Tom Moody", age: "31", address: "CA"},  
{ name: "Zahira Wasim", age: "19", address: "Islamabad"},  
{ name: "Juck Ross", age: "45", address: "London"}  
];  
db.collection("customers").insert(myobj, function(err, res) {  
if (err) throw err;  
console.log("Number of records inserted: " + res.insertedCount);  
db.close();  
});  
}); 
Enter fullscreen mode Exit fullscreen mode

Open the command terminal and run the following command:

Node insertall.js

Image description

Node.js MongoDB Select Record

The findOne() method is used to select a single data from a collection in MongoDB. This method returns the first record of the collection.

Example

(Select Single Record)

Select the first record from the ?employees? collection.

Node.js MongoDB Filter Query

The find() method is also used to filter the result on a specific parameter. You can filter the result by using a query object.

Example

Filter the records to retrieve the specific employee whose address is "Delhi".

Create a js file named "query1.js", having the following code:
Play

var http = require('http');  
var MongoClient = require('mongodb').MongoClient;  
var url = "mongodb://localhost:27017/MongoDatabase";  
MongoClient.connect(url, function(err, db) {  
if (err) throw err;  
var query = { address: "Delhi" };  
db.collection("employees").find(query).toArray(function(err, result) {  
if (err) throw err;  
console.log(result);  
db.close();  
});  
}); 
Enter fullscreen mode Exit fullscreen mode

Open the command terminal and run the following command:

Node query1.js

Image description

Node.js MongoDB Filter With Regular Expression

You can also use regular expression to find exactly what you want to search. Regular expressions can be used only to query strings.

Example

Retrieve the record from the collection where address start with letter "L".

Create a js file named "query2", having the following code:

var http = require('http');  
var MongoClient = require('mongodb').MongoClient;  
var url = "mongodb://localhost:27017/MongoDatabase";  
MongoClient.connect(url, function(err, db) {  
if (err) throw err;  
var query = { address: /^L/ };  
db.collection("employees").find(query).toArray(function(err, result) {  
if (err) throw err;  
console.log(result);  
db.close();  
});  
});  
Enter fullscreen mode Exit fullscreen mode

Open the command terminal and run the following command:

Node query2.js

Image description

Node.js MongoDB Sorting

In MongoDB, the sort() method is used for sorting the results in ascending or descending order. The sort() method uses a parameter to define the object sorting order.

Value used for sorting in ascending order:  
{ name: 1 }  
Value used for sorting in descending order:  
{ name: -1 } 
Enter fullscreen mode Exit fullscreen mode

Sort in Ascending Order
Example

Sort the records in ascending order by the name.

Create a js file named "sortasc.js", having the following code:
Play

var http = require('http');  
var MongoClient = require('mongodb').MongoClient;  
var url = "mongodb://localhost:27017/ MongoDatabase";  
MongoClient.connect(url, function(err, db) {  
if (err) throw err;  
var mysort = { name: 1 };  
db.collection("employees").find().sort(mysort).toArray(function(err, result) {  
if (err) throw err;  
console.log(result);  
db.close();  
});  
});
Enter fullscreen mode Exit fullscreen mode

Image description

Open the command terminal and run the following command:

Node sortasc.js 
Enter fullscreen mode Exit fullscreen mode

Sort in Descending Order
Example

Sort the records in descending order according to name:

Create a js file named "sortdsc.js", having the following code:

var http = require('http');  
var MongoClient = require('mongodb').MongoClient;  
var url = "mongodb://localhost:27017/ MongoDatabase";  
MongoClient.connect(url, function(err, db) {  
if (err) throw err;  
var mysort = { name: -1 };  
db.collection("employees").find().sort(mysort).toArray(function(err, result) {  
if (err) throw err;  
console.log(result);  
db.close();  
});  
}); 
Enter fullscreen mode Exit fullscreen mode

Open the command terminal and run the following command:

Node sortdsc.js 
Enter fullscreen mode Exit fullscreen mode

Image description

Node.js MongoDB Remove

In MongoDB, you can delete records or documents by using the remove() method. The first parameter of the remove() method is a query object which specifies the document to delete.

Example

Remove the record of employee whose address is Ghaziabad.

Create a js file named "remove.js", having the following code:
Play

var http = require('http');  
var MongoClient = require('mongodb').MongoClient;  
var url = "mongodb://localhost:27017/ MongoDatabase";  
MongoClient.connect(url, function(err, db) {  
if (err) throw err;  
var myquery = { address: 'Ghaziabad' };  
db.collection("employees").remove(myquery, function(err, obj) {  
if (err) throw err;  
console.log(obj.result.n + " record(s) deleted");  
db.close();  
});  
}); 
Enter fullscreen mode Exit fullscreen mode

Open the command terminal and run the following command:

Image description

Node remove.js

You can check that the record having address "Ghaziabad" is deleted and only following records are available now:

Image description

Node.js MongoDB Update

Update the document with the address "Valley 345" to name="Mickey" and address="Canyon 123":

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://127.0.0.1:27017/";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("mydb");
  var myquery = { address: "Valley 345" };
  var newvalues = { $set: {name: "Mickey", address: "Canyon 123" } };
  dbo.collection("customers").updateOne(myquery, newvalues, function(err, res) {
    if (err) throw err;
    console.log("1 document updated");
    db.close();
  });
});
Enter fullscreen mode Exit fullscreen mode

Node.js MongoDB Limit

Limit the Result
To limit the result in MongoDB, we use the limit() method.

The limit() method takes one parameter, a number defining how many documents to return.

Consider you have a "customers" collection:

customersGet your own Node.js Server
[
  { _id: 58fdbf5c0ef8a50b4cdd9a84 , name: 'John', address: 'Highway 71'},
  { _id: 58fdbf5c0ef8a50b4cdd9a85 , name: 'Peter', address: 'Lowstreet 4'},
  { _id: 58fdbf5c0ef8a50b4cdd9a86 , name: 'Amy', address: 'Apple st 652'},
  { _id: 58fdbf5c0ef8a50b4cdd9a87 , name: 'Hannah', address: 'Mountain 21'},
  { _id: 58fdbf5c0ef8a50b4cdd9a88 , name: 'Michael', address: 'Valley 345'},
  { _id: 58fdbf5c0ef8a50b4cdd9a89 , name: 'Sandy', address: 'Ocean blvd 2'},
  { _id: 58fdbf5c0ef8a50b4cdd9a8a , name: 'Betty', address: 'Green Grass 1'},
  { _id: 58fdbf5c0ef8a50b4cdd9a8b , name: 'Richard', address: 'Sky st 331'},
  { _id: 58fdbf5c0ef8a50b4cdd9a8c , name: 'Susan', address: 'One way 98'},
  { _id: 58fdbf5c0ef8a50b4cdd9a8d , name: 'Vicky', address: 'Yellow Garden 2'},
  { _id: 58fdbf5c0ef8a50b4cdd9a8e , name: 'Ben', address: 'Park Lane 38'},
  { _id: 58fdbf5c0ef8a50b4cdd9a8f , name: 'William', address: 'Central st 954'},
  { _id: 58fdbf5c0ef8a50b4cdd9a90 , name: 'Chuck', address: 'Main Road 989'},
  { _id: 58fdbf5c0ef8a50b4cdd9a91 , name: 'Viola', address: 'Sideway 1633'}
]
Enter fullscreen mode Exit fullscreen mode

Example
Limit the result to only return 5 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("mydb");
  dbo.collection("customers").find().limit(5).toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
    db.close();
  });
});
Enter fullscreen mode Exit fullscreen mode

Save the code above in a file called "demo_mongodb_limit.js" and run the file:

Run "demo_mongodb_limit.js"

C:\Users\Your Name>node demo_mongodb_limit.js
Which will give you this result:
Enter fullscreen mode Exit fullscreen mode
customers
[
  { _id: 58fdbf5c0ef8a50b4cdd9a84 , name: 'John', address: 'Highway 71'},
  { _id: 58fdbf5c0ef8a50b4cdd9a85 , name: 'Peter', address: 'Lowstreet 4'},
  { _id: 58fdbf5c0ef8a50b4cdd9a86 , name: 'Amy', address: 'Apple st 652'},
  { _id: 58fdbf5c0ef8a50b4cdd9a87 , name: 'Hannah', address: 'Mountain 21'},
  { _id: 58fdbf5c0ef8a50b4cdd9a88 , name: 'Michael', address: 'Valley 345'}
]

Enter fullscreen mode Exit fullscreen mode

Join Collections

MongoDB is not a relational database, but you can perform a left outer join by using the $lookup stage.

The $lookup stage lets you specify which collection you want to join with the current collection, and which fields that should match.

Consider you have a "orders" collection and a "products" collection:

ordersGet your own Node.js Server
[
  { _id: 1, product_id: 154, status: 1 }
]
products
[
  { _id: 154, name: 'Chocolate Heaven' },
  { _id: 155, name: 'Tasty Lemons' },
  { _id: 156, name: 'Vanilla Dreams' }
]
Enter fullscreen mode Exit fullscreen mode

Example
Join the matching "products" document(s) to the "orders" collection:

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://127.0.0.1:27017/";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("mydb");
  dbo.collection('orders').aggregate([
    { $lookup:
       {
         from: 'products',
         localField: 'product_id',
         foreignField: '_id',
         as: 'orderdetails'
       }
     }
    ]).toArray(function(err, res) {
    if (err) throw err;
    console.log(JSON.stringify(res));
    db.close();
  });
});
Enter fullscreen mode Exit fullscreen mode

Save the code above in a file called "demo_mongodb_join.js" and run the file:

Run "demo_mongodb_join.js"

C:\Users\Your Name>node demo_mongodb_join.js
Enter fullscreen mode Exit fullscreen mode

Which will give you this result:

[
  { "_id": 1, "product_id": 154, "status": 1, "orderdetails": [
    { "_id": 154, "name": "Chocolate Heaven" } ]
  }
]
Enter fullscreen mode Exit fullscreen mode

As you can see from the result above, the matching document from the products collection is included in the orders collection as an array.

How to retrive data in node js using mongo db

Here's an example of how to retrieve data in Node.js using MongoDB:

First, you need to install the MongoDB driver for Node.js. You can do this by running the following command in your terminal:

npm install mongodb
Enter fullscreen mode Exit fullscreen mode

Once you've installed the MongoDB driver, you need to create a connection to your MongoDB database. Here's an example of how to do this:

const { MongoClient } = require('mongodb');

const uri = 'mongodb://localhost:27017/my_database';

const client = new MongoClient(uri);

async function connect() {
  try {
    await client.connect();
    console.log('Connected to MongoDB');
  } catch (error) {
    console.log(error);
  }
}

connect();
Enter fullscreen mode Exit fullscreen mode

In this example, we're using the MongoClient class to create a new connection to a MongoDB database running on localhost and listening on port 27017. The uri variable contains the connection string for our database. We're then creating a new instance of the MongoClient class and connecting to the database using the connect() method. We're also using the async/await syntax to handle the connection in a non-blocking way.

Once you've established a connection to your MongoDB database, you can retrieve data from a collection using the find() method. Here's an example of how to retrieve all documents from a collection:

async function getAllDocuments(collectionName) {
  const db = client.db();
  const collection = db.collection(collectionName);
  const documents = await collection.find().toArray();
  console.log(documents);
}

getAllDocuments('users');
Enter fullscreen mode Exit fullscreen mode

In this example, we're creating a new function called getAllDocuments() that takes a collection name as an argument. We're then using the db() method to get a reference to our database, and the collection() method to get a reference to the specified collection. We're then using the find() method to retrieve all documents from the collection, and the toArray() method to convert the result to an array. Finally, we're logging the result to the console.

You can also retrieve a specific document from a collection using the findOne() method. Here's an example of how to retrieve a document with a specific ID:

async function getDocumentById(collectionName, id) {
  const db = client.db();
  const collection = db.collection(collectionName);
  const document = await collection.findOne({ _id: id });
  console.log(document);
}

getDocumentById('users', '1234');
Enter fullscreen mode Exit fullscreen mode

In this example, we're creating a new function called getDocumentById() that takes a collection name and an ID as arguments. We're then using the db() method to get a reference to our database, and the collection() method to get a reference to the specified collection. We're then using the findOne() method to retrieve the document with the specified ID, and logging the result to the console.

These are just some basic examples of how to retrieve data in Node.js using MongoDB. There are many more methods and options available for querying and manipulating data in MongoDB, so be sure to consult the official MongoDB documentation for more information.

How to retrive data in node js using mongo db join collection

To retrieve data in Node.js using MongoDB join collection and display the data, you can follow these steps:

Install the required dependencies:

mongodb
express
Enter fullscreen mode Exit fullscreen mode

You can use the following command to install these dependencies:

npm install mongodb express
Enter fullscreen mode Exit fullscreen mode

Import the required modules in your Node.js file:

const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = 'mongodb://localhost:27017';
const dbName = 'mydb';
const app = express();
Enter fullscreen mode Exit fullscreen mode

Here, we have imported the express, MongoClient, assert modules and defined the url and dbName for our MongoDB connection.

Connect to MongoDB using MongoClient.connect() method:

MongoClient.connect(url, (err, client) => {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  const db = client.db(dbName);
  // Call the required functions here

  client.close();
});
Enter fullscreen mode Exit fullscreen mode

Here, we are connecting to MongoDB using the MongoClient.connect() method and getting the db object to perform database operations.

Perform the join operation on the required collections and retrieve the data:


db.collection('orders').aggregate([
  {
    $lookup:
      {
        from: 'products',
        localField: 'product_id',
        foreignField: '_id',
        as: 'orderdetails'
      }
  }
]).toArray((err, result) => {
  assert.equal(err, null);
  console.log(result);
});
Enter fullscreen mode Exit fullscreen mode

Here, we are performing the join operation between the orders and products collections using the $lookup operator. We are matching the product_id field in the orders collection with the _id field in the products collection. We are then storing the result in the orderdetails field of the output.

Display the data:

app.get('/orders', (req, res) => {
  db.collection('orders').aggregate([
    {
      $lookup:
        {
          from: 'products',
          localField: 'product_id',
          foreignField: '_id',
          as: 'orderdetails'
        }
    }
  ]).toArray((err, result) => {
    assert.equal(err, null);
    res.send(result);
  });
});

app.listen(3000, () => {
  console.log("Server is listening on port 3000");
});
Enter fullscreen mode Exit fullscreen mode

Here, we are creating a route for /orders and retrieving the data from MongoDB using the aggregate() method. We are then sending the retrieved data as a response to the user.

This will start the server and it will listen on port 3000.

Test the API:

Open a web browser and navigate to http://localhost:3000/orders. This will display the data retrieved from MongoDB in a JSON format.

Sure, here's an example code for retrieving data from MongoDB and joining two collections in Node.js:

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

// Connection URL and database name
const url = 'mongodb://localhost:27017';
const dbName = 'mydb';

// Create a new MongoClient
const client = new MongoClient(url, { useUnifiedTopology: true });

// Use connect method to connect to the Server
client.connect(function(err) {
  if (err) throw err;

  // Get the database object
  const db = client.db(dbName);

  // Define the collections
  const ordersCollection = db.collection('orders');
  const customersCollection = db.collection('customers');

  // Join the collections
  ordersCollection.aggregate([
    { $lookup:
       {
         from: 'customers',
         localField: 'customer_id',
         foreignField: '_id',
         as: 'customer'
       }
     }
   ]).toArray(function(err, result) {
    if (err) throw err;

    // Print the joined data
    console.log(result);

    // Close the connection
    client.close();
  });
});
Enter fullscreen mode Exit fullscreen mode

In this example, we first create a new MongoClient and use it to connect to the MongoDB server. We then retrieve the database object and define the two collections that we want to join: orders and customers.

To join the collections, we use the aggregate method on the ordersCollection object, and use the $lookup operator to specify the collection to join (customers), the local field to match (customer_id), the foreign field to match (_id), and the name of the output field (customer).

Finally, we call the toArray method to retrieve the joined data as an array of objects, and print it to the console. We then close the MongoDB connection using the close method.

Top comments (0)