Skip to content

Working with MongoDB Node js Driver AQSA Spark By {Examples}

  • by

In this article, we will connect MongoDB with the Node.js driver and perform some operations. When MongoDB is combined with Node.js, it becomes an effective tool for creating quick and scalable applications.

Pre-requisites: Have MongoDB and NPM installed on the system.

1. Install MongoDB driver in node js

As a first step, let’s install MongoDB if it is not already installed. The second step is to download the MongoDB driver for Node.js and install it, we can install it using the npm command of Node.js.

The npm is a command-line tool that comes with Node.js for installing and managing packages (libraries) in a Node.js project. Here, we use the npm command to install the MongoDB driver.

# Install mongodb driver
npm install mongodb –save

The installed package is saved as a dependency in the package.json of the file by npm when the –save flag is used in the command above. This is the command’s output, as mentioned before.

2. Create the Directory

After the installation of the mongodb package to package.json, we have to create the directory where the MongoDB program will reside. These are the basic and simple commands which help us to create the directory using the command prompt.

#Create directory
mkdir newProject

Here, we named the directory newProjects and then used the following command to get into that directory.

#Getting into directory
cd newProject

Then, we used the command that initializes a new Node.js project with default values without prompting the user for any configuration options. The command is specified below.

#initialize a new Node.js project
npm init -y

Here, the init option initializes a new Node.js project by creating a package.json file, and option –y tells npm to use the default values for all the configuration options instead of prompting the user for input. It then gives the following output with a minimal set of properties, such as the project name, version, description, and entry point.

3. Connect MongoDB with the Node.js

Finally, we can connect with the MongoDB server using the node js here. The MongoClient class allows us to establish a database connection. The code to connect to a MongoDB database is provided below.

#Connection to MongoDB
const { MongoClient } = require(‘mongodb’);
const url = ‘mongodb://127.0.0.1:27017’;
const client = new MongoClient(url);
const dbName = ‘MyDatabase’;
async function main() {
await client.connect();
console.log(‘Connected successfully to server’);
const db = client.db(dbName);
const collection = db.collection(‘student’);
return ‘done.’;
}
main()
.then(console.log)
.catch(console.error)
.finally(() => client.close());

The above program connects to a MongoDB server running on the local machine at port 27017 using the MongoDB Node.js driver. Here, the MongoClient is imported from the mongodb module and is used to connect to the MongoDB server. The url variable holds the connection string to the MongoDB server, and the dbName variable holds the name of the database to connect to.

Then, the main function is declared as an async function that is responsible for establishing a connection to the MongoDB server and performing some operations on the student collection. Hence, the main function returns the string done. When the file.js file is executed, it shows that the operations were successful.

4. Insert New Documents

Now, we have performed the MongoDB operation of inserting the document in Node.js. The main() method of file.js is where the code listed below is inserted.

#nserting document in Node.js
async function main() {
const insertDocuments =
await collection.insertMany([{ name: ‘John’, age: 20 },
{ name: ‘Billy’, age: 25 },
{ name: ‘Elena’, age: 23 }]);
console.log(‘Inserted documents =>’, insertDocuments);
return ‘done.’;
}

Here, we have inserted multiple documents into the student collection using the insertMany() method of the MongoDB Node.js driver. The await option specifies waiting for the insertion operation to complete before continuing with the execution of the code. Thus, the output contains information about the insertion operation which includes the total number of documents inserted and the IDs of the inserted documents.

5. Update the Documents

Next, we performed another operation of MongoDB in the Node.js driver which is an update operation. The following code updates the document of MongoDB collection in Node.js.

#Updating documents
async function main() {
const updateDocument = await collection.updateOne({ name: ‘John’ },
{ $set: { age: 22 } });
console.log(‘Updated document =>’, updateDocument);
return ‘done.’;
}

Here, the code single document in the student collection using the updateOne() method of the MongoDB Node.js driver. As we can see the output contains the number of documents matched and the number of documents modified.

Additionally, if you want to remove the file from the document in the MongoDB collection, you can follow this link.

6. Conclusion

In conclusion, using MongoDB with Node.js provides ease of use, scalability, performance, and JSON-like documents. By following all the steps, we can connect MongoDB with Node.js and perform various operations of MongoDB.

You can also follow this link to connect MongoDB with the Node.js

 In this article, we will connect MongoDB with the Node.js driver and perform some operations. When MongoDB is combined with Node.js, it becomes an effective tool for creating quick and scalable applications. Pre-requisites: Have MongoDB and NPM installed on the system. 1. Install MongoDB driver in node js As a first step, let’s install MongoDB  Read More MongoDB 

Leave a Reply

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