0% found this document useful (0 votes)
12 views3 pages

Web Tech 8

practical web tech

Uploaded by

aayush2310008-d
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views3 pages

Web Tech 8

practical web tech

Uploaded by

aayush2310008-d
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

EXPERIMENT -08

Develop a script that uses MongoDB's aggregation framework to


perform operations like grouping, filtering, and sorting. For
instance, aggregate user data to find the average age of users in
different cities.
CODE:
const { MongoClient } = require('mongodb');

// MongoDB connection URI


const uri = 'mongodb://localhost:27017'; // Replace with your MongoDB URI if
different
const dbName = 'userDatabase'; // Replace with your database name
const collectionName = 'users'; // Replace with your collection name

async function runAggregation() {


const client = new MongoClient(uri);

try {
await client.connect();
console.log('Connected to MongoDB');

const db = client.db(dbName);
const collection = db.collection(collectionName);

// MongoDB Aggregation Pipeline


const pipeline = [
// Step 1: Filter users (e.g., age > 18)
{ $match: { age: { $gt: 18 } } },

// Step 2: Group by city and calculate average age


{
$group: {
_id: '$city',
averageAge: { $avg: '$age' },
totalUsers: { $sum: 1 },
},
},

// Step 3: Sort by average age in descending order


{ $sort: { averageAge: -1 } },
];

// Execute the aggregation pipeline


const results = await collection.aggregate(pipeline).toArray();

// Display the results


console.log('Aggregation Results:');
results.forEach((result) => {
console.log(City: ${result._id}, Average Age: ${result.averageAge.toFixed(2)},
Total Users: ${result.totalUsers});
});
} catch (error) {
console.error('Error running aggregation:', error);
} finally {
await client.close();
console.log('Disconnected from MongoDB');
}
}

// Run the aggregation function


runAggregation();

DATABASE PROVIDED TO MongoDB :


[
{ "name": "Alice", "age": 25, "city": "New York" },
{ "name": "Bob", "age": 30, "city": "Los Angeles" },
{ "name": "Charlie", "age": 35, "city": "New York" },
{ "name": "David", "age": 20, "city": "Los Angeles" },
{ "name": "Eve", "age": 22, "city": "Chicago" }
]

OUTPUT:
Connected to MongoDB
Aggregation Results:
City: New York, Average Age: 30.00, Total Users: 2
City: Los Angeles, Average Age: 25.00, Total Users: 2
City: Chicago, Average Age: 22.00, Total Users: 1
Disconnected from MongoDB

You might also like