0% found this document useful (0 votes)
4 views

Practical-8 Resource

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Practical-8 Resource

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Practical No:8

Objective
Develop a script that uses MongoDB aggregation framework to perform the operations like
grouping filtering and sorting
Theory
The MongoDB Aggregation Framework is a powerful tool for processing and transforming
data stored in MongoDB collections. It allows developers to create complex data pipelines,
similar to those found in traditional relational databases, but with the flexibility and
scalability of NoSQL databases.

Code
// Connect to the MongoDB server and select the database

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

const uri = "mongodb://localhost:27017";

const client = new MongoClient(uri);

async function run() {

try {

await client.connect();

const database = client.db('mydatabase');

const collection = database.collection('sales');

// Define the aggregation pipeline

const pipeline = [

// Match stage to filter documents

$match: {

quantity: { $gt: 10 } // Filter for documents where quantity is greater than 10

},

// Group stage to group documents by item and calculate total quantity and total price

$group: {

_id: "$item",
totalQuantity: { $sum: "$quantity" },

totalPrice: { $sum: { $multiply: ["$quantity", "$price"] } }

},

// Sort stage to sort documents by total quantity in descending order

$sort: { totalQuantity: -1 }

];

// Execute the aggregation pipeline

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

// Print the result

console.log(result);

} finally {

await client.close();

run().catch(console.dir);

Output
[

{ "_id": "orange", "totalQuantity": 20, "totalPrice": 60 },

{ "_id": "apple", "totalQuantity": 25, "totalPrice": 50 }

You might also like