MongoDB query to execute stored function?

JavaScript functions can be saved for reuse using a system collection called system.js. To store a function, use db.collection.save(), then execute it with db.eval().

Syntax

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

// Execute function
db.eval("functionName(arguments)");

Example: Store and Execute Function

Let us first create a function ?

db.system.js.save({
    _id: "displayMessage",
    value: function (data) {
        return 'The Name is: ' + data;
    }
});

This will produce the following output ?

WriteResult({
    "nMatched" : 0,
    "nUpserted" : 1,
    "nModified" : 0,
    "_id" : "displayMessage"
})

Following is the query to execute stored function ?

db.eval("displayMessage('John')");

This will produce the following output ?

The Name is: John

Key Points

  • db.eval() is deprecated and should be avoided in production environments.
  • Modern MongoDB versions recommend using aggregation pipelines or application-level functions instead.
  • Stored functions are saved in the system.js collection with an _id and value field.

Conclusion

While MongoDB allows storing JavaScript functions in system.js and executing them with db.eval(), this approach is deprecated. Use aggregation pipelines or application-side logic for better performance and security.

Updated on: 2026-03-15T02:43:38+05:30

610 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements