Pass a field value to an external function

Hi everyone,

I’m struggling with what looks like a basic operation. I’m trying to pass a field value into a function that is defined in another script in a project stage.

I’ve read about the $function operator but I’m running a Mongodb version < 4.4 (4.2.13). Then, it looks like (on the Web) $where and mapReduce() could be an alternative.

Unfortunately, even after reading the documentatio, I’m not sure what the synthax should be. Let’s consider a simple example :

External function (another script):

function external_func(field_value) { // field_value is a string
    return field_value;

What I’m trying to get (aggregation pipeline):

$project: {
    'new_field': {
                    $where: external_func(***)

I only would like to project the value of a field name after making some conversion in the external function.

Unfortunately, I tried a couple of things as an argument: external_func(this.field_name), external_func(’$field_name’), etc… but the only response I get is ""Unrecognized expression '$where'

Obviously, I’m still not very good at it :slight_smile:

If anyone has an idea, thanks a lot !

Hello @Dr_Sim ,

Welcome to The MongoDB Community! :wave:

The reason you are getting this error is because one cannot use $where in Aggregation Operations such as $project as it is not supported, $where can only be used in a find query.

Regarding Map-Reduce, it was deprecated in MongoDB v5.0 and Aggregation Pipeline is generally a better alternative to that.

Alternatively, if you really must use the Javascript function and cannot upgrade to MongoDB 4.4, you might be able to do this operation in the application side. If you’re not mandated to use the Javascript function, is it possible to translate the function into aggregation operators instead?

Lastly, $function was introduced in MongoDB v4.4 and I believe this is the functionality you’re looking for. However this would require you to upgrade to MongoDB 4.4, so this may or may not work for you.

Executing JavaScript inside an aggregation expression may decrease performance. Only use the $function operator if the provided pipeline operators cannot fulfill your application’s needs.

If you need further help, Can you please explain what this external function does?


1 Like

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