1

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Hey Joe thanks. I understood the second part. but is there any proof for your first statement that "MongoDB relies on using JavaScript call"?
The source is on github, I don't recall the exact location in the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.