0% found this document useful (0 votes)
41 views5 pages

Web - Technology Prac8 Sap2

The document outlines a practical task to develop a MongoDB script that utilizes its aggregation framework for analyzing user data, specifically to calculate the average age of users in different cities. It provides a theoretical background on MongoDB, highlighting its key features such as document storage, scalability, and rich query language. Additionally, the document includes sample code for user data analysis and activity tracking using aggregation pipelines.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views5 pages

Web - Technology Prac8 Sap2

The document outlines a practical task to develop a MongoDB script that utilizes its aggregation framework for analyzing user data, specifically to calculate the average age of users in different cities. It provides a theoretical background on MongoDB, highlighting its key features such as document storage, scalability, and rich query language. Additionally, the document includes sample code for user data analysis and activity tracking using aggregation pipelines.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

PRACTICAL: 8

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: -

MongoDB is a widely used, document-oriented NoSQL database program developed by MongoDB


Inc. It is designed to store data in a flexible, JSON-like format known as BSON (Binary JSON),
which allows for dynamic schemas. This flexibility makes MongoDB suitable for applications that
require rapid iteration and scalability.
Key Features of MongoDB
Document Storage: Data is stored in documents, which are key-value pairs similar to JSON
objects. This structure allows for complex data types, including arrays and nested documents

Scalability: MongoDB supports horizontal scaling through sharding, allowing it to handle


large volumes of data across distributed systems

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:-

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

async function analyzeUserData() {


// Connection URL and Database Name
const url = 'mongodb://localhost:27017';
const dbName = 'userAnalytics';

try {
// Connect to MongoDB
const client = await MongoClient.connect(url);
const db = client.db(dbName);
const users = db.collection('users');

// Pipeline for average age by city


const cityAgePipeline = [
{
$group: {
_id: "$city",
averageAge: { $avg: "$age" },
totalUsers: { $sum: 1 },
youngestUser: { $min: "$age" },
oldestUser: { $max: "$age" }
}
},
{
$sort: { averageAge: -1 }
},
{
$project: {
city: "$_id",
averageAge: { $round: ["$averageAge", 1] },
totalUsers: 1,
ageRange: {
$concat: [
{ $toString: "$youngestUser" },
" - ",
{ $toString: "$oldestUser" }
]
}
}
}
];

// Pipeline for user activity analysis


const activityPipeline = [
{
$match: {
lastLoginDate: {
$gte: new Date(new Date().setMonth(new Date().getMonth() - 1))
}
}
},
{
$group: {
_id: {
city: "$city",
ageGroup: {
$switch: {
branches: [
{ case: { $lt: ["$age", 25] }, then: "18-24" },
{ case: { $lt: ["$age", 35] }, then: "25-34" },
{ case: { $lt: ["$age", 45] }, then: "35-44" },
{ case: { $lt: ["$age", 55] }, then: "45-54" }
],
default: "55+"
}
}
},
activeUsers: { $sum: 1 },
averageSessionDuration: { $avg: "$averageSessionMinutes" }
}
},
{
$sort: {
"_id.city": 1,
"_id.ageGroup": 1
}
}
];

// Execute pipelines
const cityAgeResults = await users.aggregate(cityAgePipeline).toArray();
const activityResults = await users.aggregate(activityPipeline).toArray();

// Format and display results


console.log('\n=== Average Age by City ===');
cityAgeResults.forEach(result => {
console.log(`\nCity: ${result.city}`);
console.log(`Average Age: ${result.averageAge}`);
console.log(`Total Users: ${result.totalUsers}`);
console.log(`Age Range: ${result.ageRange}`);
});

console.log('\n=== User Activity Analysis ===');


let currentCity = '';
activityResults.forEach(result => {
if (currentCity !== result._id.city) {
currentCity = result._id.city;
console.log(`\nCity: ${currentCity}`);
}
console.log(` Age Group: ${result._id.ageGroup}`);
console.log(` Active Users: ${result.activeUsers}`);
console.log(` Avg Session Duration: ${Math.round(result.averageSessionDuration)}
minutes`);
});

// Close connection
await client.close();
} catch (err) {
console.error('Error:', err);
}
}

// Example usage with sample data insertion


async function insertSampleData() {
const client = await MongoClient.connect(url);
const db = client.db(dbName);
const users = db.collection('users');

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();
}

// Run the analysis


analyzeUserData();
Output:-

You might also like