How to Bind variable as a Field Name inside Aggregate using node js

Hi friends,

I have faced a problem when trying to bind the variable inside the $group. My requirement is incoming field must be bound inside the $group aggregation.

I have tried the following

let fieldName = stage
 {
            $group: {
                _id:"$$fieldName ",
                count: {$sum:1},
            },
        },

The above is not worked.it is showing an error like an undefined variable is used fieldName,

Please help to solve this

Thanks
Pravin

Hello :wave: @Pravin_Raja,

Welcome to the MongoDB Community forums :sparkles:

It seems that you are trying to bind a variable in the $group stage on the client side using the $$ operator. It’s important to note that in MongoDB, the aggregation pipeline is executed on the server side, and variables declared on the client side cannot be directly accessed within the pipeline.

However, one possible workaround is to dynamically construct the aggregation pipeline using an application code (here JavaScript). This approach will allow you to build the pipeline dynamically and inject the variable value into the $group stage. Here’s an example code snippet:

const fieldName = 'stage';
const pipeline = [
    {
        $group: {
            _id: '$' + fieldName,
            count: { $sum: 1 }
        }
    }
];
collection.aggregate(pipeline)
    .toArray()
    .then((result) => {
        console.log(result);
        // Handle the result as needed

        console.log('Find query executed...');
        console.log(result);

        client.close(); // Close the MongoDB connection
    })

In the above example, I constructed the pipeline dynamically by concatenating the field name with the $ operator to reference the field in the $group stage.

Please note that this is just one possible approach, and the actual implementation may vary depending on your specific requirements.

I hope this helps. Please feel free to reach out if you have any further questions.

Best Regards,
Kushagra

2 Likes

Hi !!!
Yeah it worked @kushagra_kesav.Thanks for Your response.

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.