Web - Technology Prac8 Sap2
Web - Technology Prac8 Sap2
AIM: -
Develop a script that uses MongoDB's aggregation framework to operations like |grouping,
filtering, and sorting. For |instance, _aggregate user data to find the laverage age of users in
different cities
.
THEORY: -
Rich Query Language: It provides a powerful query language that supports various operations,
including filtering, sorting, and aggregation of data
Indexing: MongoDB allows for various indexing options to improve query performance. This
includes single-field indexes, compound indexes, and text indexes
Aggregation Framework: The aggregation framework enables users to perform advanced data
processing and transformation operations directly within the database
Code:-
try {
// Connect to MongoDB
const client = await MongoClient.connect(url);
const db = client.db(dbName);
const users = db.collection('users');
// Execute pipelines
const cityAgeResults = await users.aggregate(cityAgePipeline).toArray();
const activityResults = await users.aggregate(activityPipeline).toArray();
// Close connection
await client.close();
} catch (err) {
console.error('Error:', err);
}
}
const sampleUsers = [
{
name: "Saptarshi Ghosh",
age: 20,
city: "Noida",
lastLoginDate: new Date(),
averageSessionMinutes: 45
},
// Add more sample users as needed
];
await users.insertMany(sampleUsers);
await client.close();
}