A MongoDB driver allows an application to communicate with a MongoDB database using a programming language. Drivers provide methods to connect to the database and perform operations such as inserting, finding, updating, and deleting documents.
A database driver is a software library that connects an application to a database server. It translates application requests into database operations and returns the results.
MongoDB provides drivers for many programming languages:
For example, a Node.js application uses the MongoDB Node.js driver to communicate with a MongoDB server.
const { MongoClient } = require("mongodb");
The MongoClient class is provided by the
official MongoDB Node.js driver.
Drivers help applications perform database operations.
Without a suitable driver or another compatible communication method, application code cannot directly use the database through its language-specific API.
The official MongoDB Node.js driver allows JavaScript applications running on Node.js to communicate with MongoDB.
Install the driver in your project:
npm install mongodb
Create a file named server.js:
const { MongoClient } = require("mongodb");
const uri = "mongodb://127.0.0.1:27017";
const client = new MongoClient(uri);
async function main() {
try {
await client.connect();
console.log("Connected to MongoDB!");
const db = client.db("school");
console.log("Database:", db.databaseName);
} catch (error) {
console.error("Connection error:", error.message);
} finally {
await client.close();
}
}
main();
Run the program:
node server.js
Make sure your local MongoDB server is running before executing this example.
Python applications commonly use PyMongo,
the official MongoDB Python driver.
Install PyMongo:
python -m pip install pymongo
Create a file named app.py:
from pymongo import MongoClient
client = MongoClient("mongodb://127.0.0.1:27017")
try:
client.admin.command("ping")
print("Connected to MongoDB!")
db = client["school"]
students = db["students"]
result = students.insert_one({
"name": "Rahul",
"age": 20,
"course": "Python"
})
print("Inserted ID:", result.inserted_id)
finally:
client.close()
Run the program:
python app.py
The program connects to MongoDB, checks the connection, inserts a document, and closes the client.
Note: Running the program repeatedly inserts additional student documents. Use a unique identifier or an upsert if you want repeatable execution without duplicate records.
Java applications can use the official MongoDB Java
driver. In a Maven project, add the synchronous driver
dependency to your pom.xml.
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>5.5.1</version>
</dependency>
The version shown is an example. Choose a currently supported version compatible with your Java environment.
Example Java program:
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
public class MongoExample {
public static void main(String[] args) {
try (MongoClient client =
MongoClients.create("mongodb://127.0.0.1:27017")) {
MongoDatabase database = client.getDatabase("school");
System.out.println(
"Connected to database: " + database.getName()
);
}
}
}
The try-with-resources statement closes the client automatically when the block finishes.
C# applications can use the official MongoDB .NET/C# driver.
Install the driver using the .NET CLI:
dotnet add package MongoDB.Driver
Example C# program:
using MongoDB.Bson;
using MongoDB.Driver;
var client = new MongoClient("mongodb://127.0.0.1:27017");
var database = client.GetDatabase("school");
var students = database.GetCollection<BsonDocument>("students");
var student = new BsonDocument
{
{ "name", "Priya" },
{ "age", 21 },
{ "course", "C#" }
};
students.InsertOne(student);
Console.WriteLine("Student inserted successfully.");
The driver provides methods such as
InsertOne(), Find(),
UpdateOne(), and DeleteOne().
PHP applications can communicate with MongoDB using
the MongoDB PHP extension together with the
mongodb/mongodb Composer library.
First, install and enable the compatible MongoDB PHP extension for your PHP environment. Then install the Composer library:
composer require mongodb/mongodb
Create a PHP file named mongodb_test.php:
<?php
require_once __DIR__ . '/vendor/autoload.php';
$client = new MongoDB\Client(
'mongodb://127.0.0.1:27017'
);
$collection = $client
->selectDatabase('school')
->selectCollection('students');
$result = $collection->insertOne([
'name' => 'Aman',
'age' => 19,
'course' => 'PHP'
]);
echo 'Inserted ID: ' . $result->getInsertedId();
?>
The PHP extension provides the lower-level driver, while the Composer library provides a more convenient PHP API.
Important: Installing the Composer package alone does not replace the required PHP extension. Confirm that the extension is enabled for the PHP version used by your web server or command line.
| MongoDB Driver | MongoDB Server |
|---|---|
| Installed or included in an application project. | Runs the database service. |
| Connects the application to MongoDB. | Stores and processes database data. |
| Provides language-specific methods. | Executes database commands and queries. |
| Examples: Node.js driver, PyMongo, PHP library. | Example: MongoDB Community Server. |
Installing a driver does not install or start the MongoDB server. The application must connect to an accessible MongoDB deployment.
A connection string specifies how the application connects to MongoDB.
Example local connection string:
mongodb://127.0.0.1:27017
Example connection string using authentication:
mongodb://username:password@localhost:27017/?authSource=admin
The authentication example is a template. Replace the credentials with valid values and configure the authentication database appropriately.
For a hosted deployment, use the connection string provided by your database administrator or hosting provider.
Security: Do not commit real passwords or secret connection strings to a public repository. Store credentials in environment variables or an appropriate secrets manager.
The MongoDB server may not be running, or the hostname and port may be incorrect.
Check the username, password, authentication database, and the user's permissions.
In Node.js, verify that the driver is installed in the correct project:
npm install mongodb
Confirm that the MongoDB PHP extension is installed and enabled for the PHP environment running the script.
Check whether the application can reach the database host and whether the network configuration allows the connection.
Complete the following tasks:
school database.1. What is the main purpose of a MongoDB driver?
2. Which package is commonly used by Python applications to connect to MongoDB?
3. What does the local connection string mongodb://127.0.0.1:27017 specify?