Master MongoDB fundamentals with our comprehensive tutorial. Learn through examples and hands-on practice.
MongoDB is a popular NoSQL database that stores data in flexible, JSON-like documents. It provides high performance, high availability, and easy scalability.
const { MongoClient } = require('mongodb');
// Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
// Database Name
const dbName = 'myproject';
async function main() {
await client.connect();
console.log('Connected successfully to MongoDB');
const db = client.db(dbName);
const collection = db.collection('documents');
return 'MongoDB connection initialized';
}
main()
.then(console.log)
.catch(console.error)
.finally(() => client.close());
Basic MongoDB connection setup using the Node.js driver
Learn how to perform Create, Read, Update, and Delete operations in MongoDB using the MongoDB Node.js driver.
// Insert a document
await collection.insertOne({
name: 'John Doe',
age: 30,
email: 'john@example.com'
});
// Find documents
const user = await collection.findOne({ name: 'John Doe' });
// Update a document
await collection.updateOne(
{ name: 'John Doe' },
{ $set: { age: 31 } }
);
// Delete a document
await collection.deleteOne({ name: 'John Doe' });
Basic CRUD operations in MongoDB
The aggregation pipeline is a powerful framework for data aggregation and transformation in MongoDB.
const result = await collection.aggregate([
// Match stage - filter documents
{ $match: { age: { $gt: 25 } } },
// Group stage - group and calculate
{ $group: {
_id: "$department",
avgAge: { $avg: "$age" },
totalEmployees: { $sum: 1 }
}
},
// Sort stage - sort by average age
{ $sort: { avgAge: -1 } }
]).toArray();
console.log(result);
Using MongoDB's aggregation pipeline for complex data analysis