mongo db and node.js (NodeJS)

npm install mongo db
{ "_id": 1, "name": "Alice", "age": 25, "category": "A" }
{ "_id": 2, "name": "Bob", "age": 30, "category": "B" }
{ "_id": 3, "name": "Charlie", "age": 25, "category": "A" }
{ "_id": 4, "name": "David", "age": 35, "category": "B" }
{ "_id": 5, "name": "Eve", "age": 30, "category": "A" }
const { Mongo Client } = require('mongo dB');

async function run Aggregation() {
    const Uri = 'mongodb://localhost:27017'; // Replace with your MongoDB URI
    const client = new Mongo Client(Uri);

    try {
        // Connect to the MongoDB server
        await client. Connect();
        console.log('Connected to MongoDB');

        const database = client. dB('test dB'); // Replace with your database name
        const collection = database. Collection('users'); // Replace with your collection name

        // Aggregation pipeline to count users by age group
        const age Aggregation = [
            {
                $bucket: {
                    group By: "$age",
                    boundaries: [0, 18, 25, 30, 40, 100],
                    default: "Unknown",
                    output: {
                        count: { $sum: 1 }
                    }
                }
            }
        ];

        console.log('Running age group aggregation...');
        const age Results = await collection. Aggregate(age Aggregation).to Array();
        console.log('Users by Age Group:', age Results);

        // Aggregation pipeline to count users by category
        const category Aggregation = [
            {
                $group: {
                    _id: "$category",
                    count: { $sum: 1 }
                }
            }
        ];

        console.log('Running category aggregation...');
        const category Results = await collection. Aggregate(category Aggregation).to Array();
        console.log('Users by Category:', category Results);

    } catch (error) {
        console. Error('Error running aggregation:', error);
    } finally {
        await client. Close();
    }
}

run Aggregation();
node aggregate.js

Read more here: Source link