Skip to content
Advertisement

MongoDB: $function operator does not support arrow function

I have following documents in testCollection:

[
  {
    "_id": ObjectId("60562f98d171d52ef0a5bb27"),
    "popularDate": ISODate("1947-08-15T00:00:00.000+05:30")
  },
  {
    "_id": ObjectId("60562f98d171d52ef0a5bb28"),
    "popularDate": ISODate("1950-01-26T00:00:00.000+05:30")
  },
  {
    "_id": ObjectId("60562f98d171d52ef0a5bb29"),
    "popularDate": ISODate("1994-01-15T00:00:00.000+05:30")
  }
]

I am using regular expression to filter documents using $function operator. I get the correct output while using Query 1.

Query 1:

let yearRegex = /^1947/;

db.testCollection.find({
    $expr: {
        $function: {
            body: function(popularDates, yearRegex) {
                return yearRegex.test(popularDates)
            },
            args: [{ $toString: "$popularDates" }, yearRegex],
            lang: "js"
        }
    }
});

Output for Query 1:

{
    "_id" : ObjectId("60562f98d171d52ef0a5bb27"),
    "popularDate" : ISODate("1947-08-15T00:00:00.000+05:30")
}

but for Query 2 I am getting all the documents and the filter is not working. In Query 2 I changed the function body to arrow function.

Query 2:

let yearRegex = /^1947/;

db.testCollection.find({
    $expr: {
        $function: {
            body: (popularDate, yearRegex) => yearRegex.test(popularDate),
            args: [{ $toString: "$popularDate" }, yearRegex],
            lang: "js"
        }
    }
});

Output for Query 2:

{
  "_id": ObjectId("60562f98d171d52ef0a5bb27"),
  "popularDate": ISODate("1947-08-15T00:00:00.000+05:30")
},
{
  "_id": ObjectId("60562f98d171d52ef0a5bb28"),
  "popularDate": ISODate("1950-01-26T00:00:00.000+05:30")
},
{
  "_id": ObjectId("60562f98d171d52ef0a5bb29"),
  "popularDate": ISODate("1994-01-15T00:00:00.000+05:30")
}

So now my question is why is arrow function not working inside $function operator, or am I missing something.

Advertisement

Answer

MongoDB relies on using javascript call to set this to the current document when calling the passed function.

Arrow functions do not have bindings to this or super (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions), so they don’t work right in server-side javascript in MongoDB.

Advertisement