Docs Menu

Docs HomeMongoDB Manual

Store a JavaScript Function on the Server


Do not store application logic in the database. There are performance limitations to running JavaScript inside of MongoDB. Application code also is typically most effective when it shares version control with the application itself.

There is a special system collection named system.js that can store JavaScript functions for reuse.

To store a function, you can use the db.collection.insertOne(), as in the following examples:

_id: "echoFunction",
value : function(x) { return x; }
_id : "myAddFunction" ,
value : function (x, y){ return x + y; }
  • The _id field holds the name of the function and is unique per database.

  • The value field holds the function definition.

These functions, saved as BSON type, are available for use from any JavaScript context, such as mapReduce and $where.

Functions saved as the deprecated BSON type JavaScript (with scope), however, cannot be used by mapReduce and $where starting in MongoDB 4.4.

What is MongoDB? →
Share Feedback
© 2023 MongoDB, Inc.


  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2023 MongoDB, Inc.