MongoDB Drivers
Connect your applications to MongoDB
🔌 What are MongoDB Drivers?
MongoDB drivers are libraries that enable applications to connect and interact with MongoDB databases. They provide language-specific APIs for performing database operations like queries, inserts, updates, and deletions.
// Node.js Driver Example
const { MongoClient } = require('mongodb');
const client = new MongoClient('mongodb://localhost:27017');
await client.connect();
Output:
✓ Connected to MongoDB successfully
Official Drivers
Node.js
JavaScript/TypeScript driver for Node.js
npm install mongodb
Python
PyMongo driver for Python applications
pip install pymongo
Java
Official Java driver for MongoDB
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
</dependency>
C# / .NET
Driver for .NET applications
dotnet add package MongoDB.Driver
🔹 Node.js Driver Example
The Node.js driver provides async/await support for modern JavaScript applications. Connect to MongoDB, perform CRUD operations, and handle errors with promises for clean, readable code.
// Install: npm install mongodb
const { MongoClient } = require('mongodb');
// Connection URI
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);
async function run() {
try {
// Connect to MongoDB
await client.connect();
console.log('Connected to MongoDB');
// Access database and collection
const database = client.db('myapp');
const users = database.collection('users');
// Insert a document
const result = await users.insertOne({
name: 'Alice',
email: '[email protected]',
age: 28
});
console.log('Inserted:', result.insertedId);
// Find documents
const user = await users.findOne({ name: 'Alice' });
console.log('Found:', user);
// Update a document
await users.updateOne(
{ name: 'Alice' },
{ $set: { age: 29 } }
);
// Delete a document
await users.deleteOne({ name: 'Alice' });
} finally {
await client.close();
}
}
run().catch(console.error);
Output:
Connected to MongoDB
Inserted: 507f1f77bcf86cd799439011
Found: { name: 'Alice', email: '[email protected]', age: 28 }
🔹 Python Driver Example
PyMongo is the official Python driver for MongoDB. It provides a Pythonic interface for database operations with support for all MongoDB features including aggregation, transactions, and change streams.
# Install: pip install pymongo
from pymongo import MongoClient
# Connect to MongoDB
client = MongoClient('mongodb://localhost:27017')
# Access database and collection
db = client['myapp']
users = db['users']
# Insert a document
result = users.insert_one({
'name': 'Bob',
'email': '[email protected]',
'age': 32
})
print(f'Inserted ID: {result.inserted_id}')
# Find documents
user = users.find_one({'name': 'Bob'})
print(f'Found: {user}')
# Find multiple documents
all_users = users.find({'age': {'$gte': 25}})
for user in all_users:
print(user['name'])
# Update a document
users.update_one(
{'name': 'Bob'},
{'$set': {'age': 33}}
)
# Delete a document
users.delete_one({'name': 'Bob'})
# Close connection
client.close()
Output:
Inserted ID: 507f191e810c19729de860ea
Found: {'_id': ObjectId('...'), 'name': 'Bob', 'email': '[email protected]', 'age': 32}
🔹 Java Driver Example
The Java driver offers both synchronous and asynchronous APIs. It provides type-safe operations with POJO mapping, making it ideal for enterprise Java applications with strong typing requirements.
// Add dependency to pom.xml or build.gradle
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
public class MongoExample {
public static void main(String[] args) {
// Connect to MongoDB
MongoClient client = MongoClients.create("mongodb://localhost:27017");
// Access database and collection
MongoDatabase database = client.getDatabase("myapp");
MongoCollection users = database.getCollection("users");
// Insert a document
Document user = new Document("name", "Charlie")
.append("email", "[email protected]")
.append("age", 35);
users.insertOne(user);
System.out.println("Inserted: " + user.getObjectId("_id"));
// Find a document
Document found = users.find(new Document("name", "Charlie")).first();
System.out.println("Found: " + found.toJson());
// Update a document
users.updateOne(
new Document("name", "Charlie"),
new Document("$set", new Document("age", 36))
);
// Delete a document
users.deleteOne(new Document("name", "Charlie"));
// Close connection
client.close();
}
}
🔹 C# / .NET Driver Example
The .NET driver provides strongly-typed access to MongoDB with LINQ support. Map C# classes to MongoDB documents automatically for seamless integration with .NET applications.
// Install: dotnet add package MongoDB.Driver
using MongoDB.Driver;
using MongoDB.Bson;
// Define a model
public class User
{
public ObjectId Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public int Age { get; set; }
}
// Connect to MongoDB
var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("myapp");
var users = database.GetCollection("users");
// Insert a document
var user = new User
{
Name = "Diana",
Email = "[email protected]",
Age = 27
};
await users.InsertOneAsync(user);
Console.WriteLine($"Inserted: {user.Id}");
// Find a document
var found = await users.Find(u => u.Name == "Diana").FirstOrDefaultAsync();
Console.WriteLine($"Found: {found.Name}");
// Update a document
await users.UpdateOneAsync(
u => u.Name == "Diana",
Builders.Update.Set(u => u.Age, 28)
);
// Delete a document
await users.DeleteOneAsync(u => u.Name == "Diana");
🔹 Connection String Format
MongoDB connection strings specify how to connect to your database:
// Local MongoDB
mongodb://localhost:27017
// MongoDB Atlas (cloud)
mongodb+srv://username:[email protected]/database
// With authentication
mongodb://username:password@localhost:27017/database
// With options
mongodb://localhost:27017/database?retryWrites=true&w=majority
// Multiple hosts (replica set)
mongodb://host1:27017,host2:27017,host3:27017/database?replicaSet=myReplSet
🔹 Common Driver Features
All official drivers support these features:
- CRUD Operations: Create, read, update, delete documents
- Aggregation: Complex data processing pipelines
- Indexes: Create and manage database indexes
- Transactions: Multi-document ACID transactions
- Change Streams: Real-time data change notifications
- Connection Pooling: Efficient connection management
🔹 Best Practices
Follow these guidelines when using drivers:
- Reuse connections: Create one client and reuse it
- Handle errors: Always use try-catch blocks
- Close connections: Close clients when done
- Use connection pooling: Let drivers manage connections
- Set timeouts: Configure appropriate timeout values
- Keep drivers updated: Use the latest stable version