MongoDB Node.js Driver

Connect and interact with MongoDB using JavaScript

🚀 What is MongoDB Node.js Driver?

The MongoDB Node.js driver allows you to connect your JavaScript applications to MongoDB databases. It provides a simple and powerful API for performing database operations using modern JavaScript syntax and promises.


// Simple connection example
const { MongoClient } = require('mongodb');
const client = new MongoClient('mongodb://localhost:27017');
await client.connect();
console.log('Connected to MongoDB!');
                                    

Key Features

🔌

Easy Connection

Connect to MongoDB with minimal code

MongoClient Connection Pooling Auto-reconnect
📊

CRUD Operations

Create, Read, Update, Delete data easily

insertOne find updateMany

Async/Await

Modern JavaScript promise support

Promises Async Functions Error Handling
🔍

Aggregation

Powerful data processing pipelines

$match $group $sort

🔹 Installation

Install the MongoDB Node.js driver using npm. This package provides all the tools you need to interact with MongoDB from your Node.js applications, including connection management and database operations.

# Install MongoDB driver
npm install mongodb

# Or with Yarn
yarn add mongodb

🔹 Connecting to MongoDB

Establish a connection to your MongoDB database using the MongoClient. The connection string specifies the database location, and you can add options for authentication and connection pooling.

const { MongoClient } = require('mongodb');

// Connection URI
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);

async function connect() {
    try {
        await client.connect();
        console.log('Connected successfully to MongoDB');
        
        const database = client.db('myDatabase');
        const collection = database.collection('users');
        
        return collection;
    } catch (error) {
        console.error('Connection error:', error);
    }
}

connect();

🔹 Insert Documents

Add new documents to your MongoDB collections using insertOne for single documents or insertMany for multiple documents. Each document is stored as a JSON-like object with automatic ID generation.

// Insert a single document
const user = {
    name: 'John Doe',
    email: '[email protected]',
    age: 30
};

const result = await collection.insertOne(user);
console.log('Inserted ID:', result.insertedId);

// Insert multiple documents
const users = [
    { name: 'Alice', email: '[email protected]', age: 25 },
    { name: 'Bob', email: '[email protected]', age: 35 }
];

const multiResult = await collection.insertMany(users);
console.log('Inserted count:', multiResult.insertedCount);

Output:

Inserted ID: 507f1f77bcf86cd799439011

Inserted count: 2

🔹 Find Documents

Query your MongoDB collections to retrieve documents. Use find() to get multiple documents or findOne() for a single document. You can filter results using query objects with various operators.

// Find all documents
const allUsers = await collection.find({}).toArray();
console.log('All users:', allUsers);

// Find with filter
const adults = await collection.find({ age: { $gte: 18 } }).toArray();
console.log('Adult users:', adults);

// Find one document
const user = await collection.findOne({ name: 'John Doe' });
console.log('Found user:', user);

// Find with projection (select specific fields)
const names = await collection
    .find({})
    .project({ name: 1, email: 1, _id: 0 })
    .toArray();
console.log('Names only:', names);

Output:

All users: [{ name: 'John Doe', email: '[email protected]', age: 30 }, ...]

Found user: { name: 'John Doe', email: '[email protected]', age: 30 }

🔹 Update Documents

Modify existing documents in your collection using update operations. Use updateOne to modify a single document or updateMany to update multiple documents that match your filter criteria.

// Update one document
const updateResult = await collection.updateOne(
    { name: 'John Doe' },
    { $set: { age: 31, city: 'New York' } }
);
console.log('Modified count:', updateResult.modifiedCount);

// Update many documents
const multiUpdate = await collection.updateMany(
    { age: { $lt: 30 } },
    { $set: { status: 'young' } }
);
console.log('Updated:', multiUpdate.modifiedCount);

// Increment a value
await collection.updateOne(
    { name: 'John Doe' },
    { $inc: { age: 1 } }
);

Output:

Modified count: 1

Updated: 2

🔹 Delete Documents

Remove documents from your collection using delete operations. Use deleteOne to remove a single document or deleteMany to remove all documents matching your filter criteria.

// Delete one document
const deleteResult = await collection.deleteOne({ name: 'John Doe' });
console.log('Deleted count:', deleteResult.deletedCount);

// Delete many documents
const multiDelete = await collection.deleteMany({ age: { $lt: 18 } });
console.log('Deleted:', multiDelete.deletedCount);

// Delete all documents in collection
const deleteAll = await collection.deleteMany({});
console.log('All deleted:', deleteAll.deletedCount);

Output:

Deleted count: 1

Deleted: 3

🔹 Aggregation Pipeline

Use aggregation pipelines to perform complex data processing and analysis. Pipelines consist of multiple stages that transform documents, allowing you to filter, group, sort, and compute values across your data.

// Aggregation example
const pipeline = [
    { $match: { age: { $gte: 18 } } },
    { $group: { 
        _id: '$city', 
        avgAge: { $avg: '$age' },
        count: { $sum: 1 }
    }},
    { $sort: { avgAge: -1 } }
];

const results = await collection.aggregate(pipeline).toArray();
console.log('Aggregation results:', results);

Output:

Aggregation results: [{ _id: 'New York', avgAge: 32, count: 5 }, ...]

🔹 Error Handling

Implement proper error handling to manage connection issues and database errors. Always use try-catch blocks with async/await and ensure you close connections properly to prevent resource leaks.

async function safeOperation() {
    const client = new MongoClient(uri);
    
    try {
        await client.connect();
        const collection = client.db('myDB').collection('users');
        
        const result = await collection.insertOne({ name: 'Test' });
        console.log('Success:', result.insertedId);
        
    } catch (error) {
        console.error('Error occurred:', error.message);
    } finally {
        await client.close();
        console.log('Connection closed');
    }
}

safeOperation();

🧠 Test Your Knowledge

Which method is used to insert a single document?