Functions in MongoDB with Example

Functions in MongoDB will be saved under MongoDB server. There is a System-defined collection called system.js, it has an ability to store JavaScript functions. To Create or Store JavaScript function db.collection.save() is the syntax used. It’s not recommended to create business logic under these functions, it degrades the Database performance.

Name of the function should be given under _id section.
Function logic and should be given under value section.

Syntax :

db.system.js.save(
      {
_id:"addNumbers",
value: function(a,b) { return a+b; }
       }
)

To call the above function

addNumbers(2,4);