I’m testing MongoDB and here is a bit of example that took me by surprise:
> function compare(a,b) { return (a==b); }
and then to list my collection:
> db.myCol.find()
{ "_id:" : ObjectId("..."), "name" : "mongo" }
{ "_id:" : ObjectId("..."), "x" : 3 }
{ "_id:" : ObjectId("..."), "name" : "mongo", "notName" : "wow" }
and – to be perfectly sure:
> compare('mongo','mongo')
true
and the weird part:
> db.myCol.find( { $where : "compare(this.name,'mongo')" } )
{ "_id:" : ObjectId("..."), "x" : 3 }
> db.myCol.find( { $where : "this.name=='mongo'" } )
{ "_id:" : ObjectId("..."), "name" : "mongo" }
{ "_id:" : ObjectId("..."), "name" : "mongo", "notName" : "wow" }
I would expect the query to have strictly opposite setting.
The reason that you are getting weird results is because you are not actually running the compare function you defined. It was defined locally, but you are executing the command remotely on the mongodb instance. What is really happening is the builtin compare is being used:
And here is how you can tell:
There is a doc page on Server-side Code Execution which explains how to store a function on the server. But, it also explains that server-side functions should not be used when possible.