MongoDb recommends that "In general, you should use $where only when you can’t express your query using another operator" due to perframce reasons. However, it appears that we can store Javascript functions server-side using the special table system.js.
So instead of doing this:
db.myCollection.find( { $where: function() { return this.credits == this.debits; } } );
Do this instead:
db.system.js.save({ _id : 'queryFunction` , value : function() { return this.credits == this.debits; } });
...
db.myCollection.find( { $where: 'queryFunction' ); //not sure about syntax
Would the second variant reap any performance benefits; and if so, are they significant?
References:
It won't help.
In either case the function will be loaded as string and compiled to a javascript function before it is executed by MongoDBs Javascript engine for every single document. Whether you load it via network or via a query to system.js won't make much of a difference, and even when it would, the bulk of the runtime would be the execution of the function in most cases.