0% found this document useful (0 votes)
7 views4 pages

WT Exp 08

Uploaded by

Akul Kumar
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)
7 views4 pages

WT Exp 08

Uploaded by

Akul Kumar
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/ 4

Experiment- 08

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

Install MongoDB Node.js Driver:


npm install mongodb

MongoDB Setup:
{
"name": "Kashif Naseem",

"age": 21,

"city": "New Delhi"

Code:

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


const uri = "mongodb://localhost:27017";
const dbName = "exampleDB";
const collectionName = "users";

(async function ()

const client = new MongoClient(uri);

try

await client.connect();

console.log("Connected to MongoDB");

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

const pipeline = [

$match: {age: { $gte: 18}},


},

$group:

_id: "$city", averageAge: {$avg: "$age"}, age,


totalUsers: {$sum: 1}

},
},

$sort: { averageAge: -1},

},

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

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 during aggregation:", error);

}
finally
{

await client.close();
}

})();
Output:
User Collection:

You might also like