:) I have run into an error using $function inside of an aggregation with MongoDB. I have an aggregation which should start with:
db.collection.aggregate([
 {
   $addFields: {
      geohash: {
        $function: {
           body: function (coord1, coord2) {
             let geohash = Geohash.encode(coord1, coord2);
             return geohash
           },
          args: [
            "$location.coordinates[0]",
            "$location.coordinates[1]",
           ],
           lang: "js",
         },
       },
    },
  },
])
However when i run the query it gives me this error: UnhandledPromiseRejectionWarning: MongoError: Invalid $addFields :: caused by :: The body function must be specified.
I am on version 4.4 of Mongo and running this code inside a Node.Js function. Any help would be much appreciated. Thanks in forward. :)
Btw, as reference i used this doc: https://docs.mongodb.com/manual/reference/operator/aggregation/function/
i try the same thing before and i found out, the function body has to be string and it seem you can not access function outside. so the solution for your issue could be something like this:
db.collection.aggregate([
 {
   $addFields: {
      geohash: {
        $function: {
           body: `function (coord1, coord2) {
             // NOTE: you need to define Geohash inside the function
             let geohash = Geohash.encode(coord1, coord2);
             return geohash
           }`,
          args: [
            "$location.coordinates[0]",
            "$location.coordinates[1]",
           ],
           lang: "js",
         },
       },
    },
  },
])
this is what i try before:
const updateDocEx = [{
      $set: {
        status: 'Modified',
        comments: {
          $function: {body: `function (val, newVal) {
            const vx = '';
            const v1 = !val ? newVal : vx.concat(val, ',', newVal);
            const v2 = v1.split(',');
            const v3 = [...new Set(v2)];
            return v3.join(',');
          }`, args: ['$comments', 'A5'], lang: 'js'}
        },
        lastUpdate: '$$NOW'
      },
    }];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With