2024-11-10 | Tag: MongoDB
Learn how to use MongoDB to store and retrieve data efficiently.
MongoDB is a NoSQL database that stores data in flexible, JSON-like documents. This allows for faster, more efficient data storage and retrieval, especially for large-scale applications with complex data structures.
Key Features of MongoDB:
- **Flexible Schema**: Data is stored in documents, allowing for a dynamic schema.
- **Scalability**: MongoDB supports horizontal scaling, making it suitable for large datasets.
- **Rich Queries**: Offers a rich query language with powerful features like aggregation.
- **High Performance**: Optimized for high-throughput operations and low-latency data access.
- **Replication & Fault Tolerance**: Provides redundancy and high availability with replica sets.
Example: Setting Up a Mongoose Model
// Install dependencies
npm install mongoose
// server.js
const mongoose = require('mongoose');
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/mydb', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// Define a schema
const userSchema = new mongoose.Schema({
name: String,
age: Number,
email: { type: String, required: true },
createdAt: { type: Date, default: Date.now },
});
// Create a model
const User = mongoose.model('User', userSchema);
// Add a new user
async function createUser() {
try {
const user = new User({ name: 'Jane Doe', age: 25, email: 'jane.doe@example.com' });
const result = await user.save();
console.log('User Created:', result);
} catch (error) {
console.error('Error creating user:', error);
}
}
createUser();
Example: Querying Data with Filters and Projections
// Find all users older than 20, return only name and email
async function findUsers() {
try {
const users = await User.find({ age: { $gt: 20 } }, 'name email');
console.log('Users Found:', users);
} catch (error) {
console.error('Error finding users:', error);
}
}
findUsers();
Example: Updating Documents
// Update a user's age by their name
async function updateUser() {
try {
const result = await User.updateOne({ name: 'Jane Doe' }, { $set: { age: 26 } });
console.log('Update Result:', result);
} catch (error) {
console.error('Error updating user:', error);
}
}
updateUser();
Example: Deleting Documents
// Delete a user by their email
async function deleteUser() {
try {
const result = await User.deleteOne({ email: 'jane.doe@example.com' });
console.log('Delete Result:', result);
} catch (error) {
console.error('Error deleting user:', error);
}
}
deleteUser();
Example: Adding Custom Validation
// Define a schema with custom validation
const productSchema = new mongoose.Schema({
name: { type: String, required: true },
price: {
type: Number,
required: true,
validate: {
validator: (value) => value > 0,
message: 'Price must be greater than zero',
},
},
});
// Create a model
const Product = mongoose.model('Product', productSchema);
// Add a new product
async function createProduct() {
try {
const product = new Product({ name: 'Laptop', price: -100 });
const result = await product.save();
console.log('Product Created:', result);
} catch (error) {
console.error('Validation Error:', error.message);
}
}
createProduct();
Example: Aggregation Pipeline
// Calculate average age of all users
async function aggregateUsers() {
try {
const result = await User.aggregate([
{ $group: { _id: null, averageAge: { $avg: '$age' } } }
]);
console.log('Average Age:', result);
} catch (error) {
console.error('Aggregation Error:', error);
}
}
aggregateUsers();
MongoDB with Mongoose provides powerful tools for building scalable, maintainable, and feature-rich applications.
Using MongoDB with Mongoose simplifies complex data operations and accelerates application development.