How to work with Stored JavaScript in MongoDB?

MongoDB allows you to store JavaScript functions in the system.js collection for reuse across database operations. These stored functions can be saved using db.system.js.save() and executed with db.eval().

Syntax

db.system.js.save({
    _id: "functionName",
    value: function (parameters) {
        // Function logic here
        return result;
    }
});

Example: Creating a Stored Function

Let's create a function that formats a return message ?

db.system.js.save({
    _id: "returnValue",
    value: function (data) {
        return 'The value==== ' + data;
    }
});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Executing the Stored Function

Call the stored function using db.eval() ?

db.eval("returnValue(20)");
WARNING: db.eval is deprecated
The value==== 20

Key Points

  • The _id field serves as the function name for later reference.
  • The value field contains the actual JavaScript function code.
  • db.eval() is deprecated in newer MongoDB versions - consider using aggregation pipeline or application-level logic instead.

Conclusion

While MongoDB supports stored JavaScript functions through the system.js collection, db.eval() is deprecated. Modern applications should handle complex logic at the application level rather than storing JavaScript in the database.

Updated on: 2026-03-15T03:26:43+05:30

507 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements