Native MongoDB driver for Node.js - GeeksforGeeks

08 Oct, 2021
The native MongoDB driver for Node.JS is a dependency that allows our JavaScript application to interact with the NoSQL database, either locally or on the cloud through MongoDB Atlas. We are allowed to use promises as well as callbacks that gives us greater flexibility in using ES6 features. 
In order to start working with the MongoDB driver, we shall first create a new folder and initialize our project: 
npm init -y

Here, -y is a flag which will initialize our project with default values. 
We will install the MongoDB driver and save it as a dependency with the following command: 
npm install mongodb --save

In our JavaScript entry point file, for the sake of convenience, we shall name app.js and we will write the following code to connect to the server: 
JavaScript
// Importing MongoClient from mongodb driverconst { MongoClient } = require('mongodb');  // Conencting to a local portconst uri = 'mongodb://127.0.0.1:27017';  const client = new MongoClient(uri, {    useUnifiedTopology: true,    useNewUrlParser: true});  connect();  // ESNext syntax using async-awaitasync function connect() {    try {        await client.connect();        const db = client.db('cars');        console.log(    `Successfully connected to db ${db.databaseName}`);    }    catch (err) {        console.error(`we encountered ${err}`);    }    finally {        client.close();    }}
Output:  
Successfully connected to db cars
Now that we have made the connection, let us see some basic Insertion, Read, Update and Delete Operations on our database:Insertion and Read: In the following code snippet we are going to deal with Insertion and Read operation.
JavaScript
const { MongoClient } = require('mongodb');const uri = 'mongodb://127.0.0.1:27017';  const client = new MongoClient(uri, {     useUnifiedTopology: true,     useNewUrlParser: true });  connect();  async function connect() {    try {        await client.connect();        const db = client.db('cars');        console.log(    `Successfully connected to db ${db.databaseName}`);          const sportsCars = db.collection('SportsCars');              // Insertion        const cursorInsertion = await sportsCars.insertMany([            {                'company': 'mercedes',                'series': 'Black Series',                'model': 'SLS AMG'            },            {                'company': 'Audi',                'series': 'A series',                'model': 'A8'            }]);        console.log(cursorInsertion.insertedCount);                  // Display        const cursorFind = sportsCars.find();        const data = await cursorFind.toArray();        console.table(data);    }    catch (err) {        console.error(`we encountered ${err}`);    }    finally {        client.close();    }}
Explanation: A collection called sports cars is created using the collections() method. For Insertion, we use the two following methods:  
insertMany() method: This method is used to insert more than one entry into the database with the help of cursors. In this case, it takes an array of objects as parametes. The method returns a promise, hence we used the await keyword. Alternatively, the method insertOne() is used to insert a single document into the table.InsertedCount: This function is used to count the number of insertions that were made.
insertMany() method: This method is used to insert more than one entry into the database with the help of cursors. In this case, it takes an array of objects as parametes. The method returns a promise, hence we used the await keyword. Alternatively, the method insertOne() is used to insert a single document into the table.
InsertedCount: This function is used to count the number of insertions that were made.
For Display we used the following methods:
find(): This method is used to find all the documents in the database with the help of cursors.toArray(): This method uses the cursor element received from the find() method to store the database in an array of objects. This method returns a promise, hence we have used the keyword await.
find(): This method is used to find all the documents in the database with the help of cursors.
toArray(): This method uses the cursor element received from the find() method to store the database in an array of objects. This method returns a promise, hence we have used the keyword await.
The Output of the Snippet is as follows:
Update: The following code snippet will help us to update a database element and then we shall display the updated database:
JavaScript
const { MongoClient } = require('mongodb');const uri = 'mongodb://127.0.0.1:27017';  const client = new MongoClient(uri, {    useUnifiedTopology: true,     useNewUrlParser: true });  connect();  async function connect() {    try {        await client.connect();        const db = client.db('cars');          const sportsCars = db.collection('SportsCars');        //update        const cursorUpdate = await sportsCars.updateOne(            { "company": "mercedes" },            { "$set": { "status": "sold" } }        );          console.log(cursorUpdate.modifiedCount);                  // Display        const cursorFind = sportsCars.find();        const data = await cursorFind.toArray();        console.table(data);    }    catch (err) {        console.error(`we encountered ${err}`);    }    finally {        client.close();    }}
Explanation: We use the following methods for updating the database:
updateOne() method: This methods allows us to update one entry. The first argument it takes is a key-value pair corresponding to the database entry as we want to update. It can be any of the properties that the element possesses. The second argument is an update command $set, which is paired with an object. The object is again a key-value pair of either an existing or a new property. If the property already exists, then the property is updated with the value passed. If it does not exist, then it is added. This method returns a promise, hence we use the keyword await. Alternatively, updateMany() method can be used to update multiple documents.modifiedCount: This method is called on the cursor element received from the previous method and gives us a count of the number of entries updated.
updateOne() method: This methods allows us to update one entry. The first argument it takes is a key-value pair corresponding to the database entry as we want to update. It can be any of the properties that the element possesses. The second argument is an update command $set, which is paired with an object. The object is again a key-value pair of either an existing or a new property. If the property already exists, then the property is updated with the value passed. If it does not exist, then it is added. This method returns a promise, hence we use the keyword await. Alternatively, updateMany() method can be used to update multiple documents.
modifiedCount: This method is called on the cursor element received from the previous method and gives us a count of the number of entries updated.
Output:  
Deleting an Entry: In the following snippet, we will delete an entry based on series:
JavaScript
const { MongoClient } = require('mongodb');const uri = 'mongodb://127.0.0.1:27017';  const client = new MongoClient(uri, {     useUnifiedTopology: true,    useNewUrlParser: true });  connect();  async function connect() {    try {        await client.connect();        const db = client.db('cars');          const sportsCars = db.collection('SportsCars');        //Delete        const cursorDelete = await sportsCars                .deleteOne({ "series": "A series" });          console.log(cursorDelete.deletedCount);                  // Display        const cursorFind = sportsCars.find();        const data = await cursorFind.toArray();        console.table(data);    }    catch (err) {        console.error(`we encountered ${err}`);    }    finally {        client.close();    }}
Explanation: We use the following methods to delete the entry “company” : “Audi” from the database:
deleteOne: This method is used to delete one entry from the database. It takes in a key-value pair which corresponds to the entry that we want to delete. This method returns a promise. Hence, we use the keyword await. Alternatively, deleteMany() method can be used to delete multiple documents at once.deletedCount: This method is called on the cursor element received from the previous method and it returns the number of deletions that were made.
deleteOne: This method is used to delete one entry from the database. It takes in a key-value pair which corresponds to the entry that we want to delete. This method returns a promise. Hence, we use the keyword await. Alternatively, deleteMany() method can be used to delete multiple documents at once.
deletedCount: This method is called on the cursor element received from the previous method and it returns the number of deletions that were made.
Output:
Hence, Node and MongoDB can be easily used to make efficient backend CRUD apis.
Node.js-Misc
Picked
MongoDB
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Spring Boot JpaRepository with Example
Aggregation in MongoDB
Mongoose Populate() Method
MongoDB - Check the existence of the fields in the specified collection
How to build a basic CRUD app with Node.js and ReactJS ?
Installation of Node.js on Linux
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
Node.js fs.readFile() Method