MongoDB is a popular NoSQL document database that stores data in flexible, JSON-like documents called BSON (Binary JSON). Unlike traditional relational databases, MongoDB doesn't require a predefined schema, making it ideal for applications with evolving data requirements and rapid development cycles.
// Connect to MongoDB
const { MongoClient } = require('mongodb');
const client = new MongoClient('mongodb://localhost:27017');
// Insert a document
await db.collection('users').insertOne({
name: 'John Doe',
email: 'john@example.com',
age: 30,
skills: ['JavaScript', 'MongoDB', 'Node.js'],
address: {
street: '123 Main St',
city: 'New York',
zipCode: '10001'
},
createdAt: new Date()
});
// Find documents
const users = await db.collection('users').find({
age: { $gte: 25 },
skills: { $in: ['JavaScript'] }
}).toArray();
// Update a document
await db.collection('users').updateOne(
{ email: 'john@example.com' },
{
$set: { age: 31 },
$push: { skills: 'React' }
}
);
// Delete a document
await db.collection('users').deleteOne({
email: 'john@example.com'
});
// Aggregation pipeline
const result = await db.collection('users').aggregate([
{ $match: { age: { $gte: 25 } } },
{ $group: {
_id: '$city',
count: { $sum: 1 },
avgAge: { $avg: '$age' }
}},
{ $sort: { count: -1 } }
]).toArray();
// Basic queries
db.users.find({ name: 'John Doe' })
db.users.find({ age: { $gt: 25 } })
db.users.find({ skills: { $in: ['JavaScript', 'Python'] } })
// Complex queries with operators
db.users.find({
$and: [
{ age: { $gte: 25 } },
{ skills: { $size: { $gte: 3 } } }
]
})
// Text search
db.users.find({ $text: { $search: 'developer' } })
// Geospatial queries
db.locations.find({
location: {
$near: {
$geometry: { type: 'Point', coordinates: [-73.9857, 40.7484] },
$maxDistance: 1000
}
}
})
// Aggregation examples
db.users.aggregate([
{ $match: { age: { $gte: 25 } } },
{ $group: {
_id: '$department',
totalUsers: { $sum: 1 },
avgSalary: { $avg: '$salary' }
}},
{ $sort: { avgSalary: -1 } },
{ $limit: 10 }
])
Average MongoDB Developer Salary
Of Modern Apps Use NoSQL
MongoDB-Related Job Openings
Join thousands of professionals who've advanced their careers with Lead With Skills. Learn MongoDB, database design, and modern data management from industry experts.