mongodb-drivers

MongoDB Drivers

In this post I am going to explore how to use MongoDB in your application.

The MongoDB Shell (mongosh) is great, but generally you will need to use MongoDB in your application. To do this, MongoDB has many language drivers.

The language drivers allow you to interact with your MongoDB database using the methods you’ve learned so far in `mongosh` but directly in your application.

These are the current officially supported drivers:

There are other community supported libraries as well.

Let’s see how to use the drivers using Node.js

Node.js Database Interaction

For this tutorial, we will use a MongoDB Atlas database. If you don’t already have a MongoDB Atlas account, you can create one for free at MongoDB Atlas.

We will also use the “sample_mflix” database loaded from our sample data in my previous post section Sending a Data API Request

MongoDB Node.js Driver Installation

To use MongoDB with Node.js, you will need to install the mongodb package in your Node.js project.

Use the following command in your terminal to install the mongodb package:

npm install mongodb
added 14 packages, and audited 46 packages in 3s
2 packages are looking for funding
run `npm fund` for details

Run the following:

C:\Users\default1> npm fund
default1
`-- https://github.com/sponsors/twbs
| `-- bootstrap@5.2.2
`-- https://opencollective.com/popperjs
`-- @popperjs/core@2.11.6

We can now use this package to connect to a MongoDB database.

Create an index.js file in your project directory.

index.js

Connection String

In order to connect to our MongoDB Atlas database, we’ll need to get our connection string from the Atlas dashboard.

  1. Go to Database then click the CONNECT button on your Cluster.

2. Choose Connect your application  and select Drivers, and choose Node.js

3. In your project folder install mongodb:

npm install mongodb

4. Add your connection string into your application code

then copy your connection string.

Example: mongodb+srv://mehzan07:<password>@cluster0.vdvjqwz.mongodb.net/?retryWrites=true&w=majority

You will need to replace the  <password>, and <cluster> with your MongoDB Atlas, password, and cluster string.

5. Press to View full code to show full code

6. copy the code and add to your Index file as following:

Connecting to MongoDB

In the index file change the password to your password

index.js

const { MongoClient, ServerApiVersion } = require('mongodb');
const uri = "mongodb+srv://mehzan07:<password>@cluster0.vdvjqwz.mongodb.net/?retryWrites=true&w=majority";
// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(uri, {
  serverApi: {
    version: ServerApiVersion.v1,
    strict: true,
    deprecationErrors: true,
  }
});
async function run() {
  try {
    // Connect the client to the server	(optional starting in v4.7)
    await client.connect();
    // Send a ping to confirm a successful connection
    await client.db("admin").command({ ping: 1 });
    console.log("Pinged your deployment. You successfully connected to MongoDB!");
  } finally {
    // Ensures that the client will close when you finish/error
    await client.close();
  }
}
run().catch(console.dir);

Run this file in your terminal.

node index.js

the result is as following image:

mongodb-drivers-1.png

In case of error, maybe you need run the following:

npm install -g mongodb

CRUD & Document Aggregation

Just as we did using mongosh, we can use the MongoDB Node.js language driver to create, read, update, delete, and aggregate documents in the database.

Expanding on the previous example, we can replace the collection.findOne() with find()insertOne()insertMany()updateOne()updateMany()deleteOne()deleteMany(), or aggregate().

Exmaple

InsertMany()

Add the following code after: “// Add CRUD functions here” to insert a document:

/ get db and collection then findOne
const db = client.db('sample_mflix');
const collection = db.collection('movies');

// Insert document in the collection
    const insertResult = await collection.insertMany([{ a: 1 }, { a: 2 }, { a: 3 }]);
console.log('Inserted documents =>', insertResult);

The new index file shall be as following:

index.js:

const { MongoClient, ServerApiVersion } = require('mongodb');
 const uri = "mongodb+srv://mehzan07:Sahand012@cluster0.vdvjqwz.mongodb.net/?retryWrites=true&w=majority"; 
// Create a MongoClient with a MongoClientOptions object to set the Stable API version
 const client = new MongoClient(uri, { serverApi: { version: ServerApiVersion.v1, strict: true, deprecationErrors: true, } }); 
async function run()
 {
 try
 { 
// Connect the client to the server (optional starting in v4.7) 
await client.connect(); 
// Send a ping to confirm a successful connection 
await client.db("admin").command({ ping: 1 }); 
console.log("Pinged your deployment. You successfully connected to MongoDB!");

// Add CRUD functions here

// get db and collection then findOne
const db = client.db('sample_mflix');
    const collection = db.collection('movies');

    // Insert document in the collection
    const insertResult = await collection.insertMany([{ a: 1 }, { a: 2 }, { a: 3 }]);
console.log('Inserted documents =>', insertResult);


 }

 finally 
{
 // Ensures that the client will close when you finish/error 
await client.close();
 }
 }
 run().catch(console.dir);

Run the new index.js file

node index.js

Result shall be:

/mongodb-drivers-3.png

FindOne()

Add the following code instead of insert code:

// Find the first document in the collection
    const first = await collection.findOne();
  console.log(first);

The new index.js file:

const { MongoClient, ServerApiVersion } = require('mongodb');
 const uri = "mongodb+srv://mehzan07:Sahand012@cluster0.vdvjqwz.mongodb.net/?retryWrites=true&w=majority"; 
// Create a MongoClient with a MongoClientOptions object to set the Stable API version
 const client = new MongoClient(uri, { serverApi: { version: ServerApiVersion.v1, strict: true, deprecationErrors: true, } }); 
async function run()
 {
 try
 { 
// Connect the client to the server (optional starting in v4.7) 
await client.connect(); 
// Send a ping to confirm a successful connection 
await client.db("admin").command({ ping: 1 }); 
console.log("Pinged your deployment. You successfully connected to MongoDB!");

// Add CRUD functions here

// get db and collection then findOne
const db = client.db('sample_mflix');
    const collection = db.collection('movies');


// Find the first document in the collection
   const first = await collection.findOne();
   console.log(first);

 }

 finally 
{
 // Ensures that the client will close when you finish/error 
await client.close();
 }
 }
 run().catch(console.dir);

run the new index.js file

node index.js

Result shall be:

/mongodb-drivers-4.png

You can test with update, delete in a little change in the above code.

 

Conclusion

In this post I have explored MongoDB drivers, and descried  Node.js drivers,  and how to install MongoDB Node.js Driver, connection string and how to connect to MongoDB.

My Next post describes MongoDB Charts, how to create Charts from dashboard

This post is part of MongoDB-Step by step

Back to home page

 

 

Leave a Reply

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