How to create MongoDB stored procedure?

MongoDB allows you to create stored procedures (server-side JavaScript functions) using the db.system.js collection. These functions are stored on the server and can be called using db.eval().

Syntax

db.system.js.save({
    _id: "yourStoredProcedueName",
    value: function(argument1, argument2, ...argumentN) {
        // function body
        return result;
    }
});

Example: Create Addition Function

Let's create a stored procedure that adds two numbers ?

db.system.js.save({
    _id: "addTwoValue",
    value: function(a, b) {
        return a + b;
    }
});
WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : "addTwoValue" })

Calling the Stored Procedure

Use db.eval() to execute the stored procedure ?

db.eval("return addTwoValue(100, 25)");
125

Important Note

Warning: The db.eval() method and server-side JavaScript are deprecated as of MongoDB 3.0 and removed in MongoDB 4.2. For modern MongoDB applications, use aggregation pipelines or application-level functions instead of stored procedures.

Conclusion

MongoDB stored procedures use db.system.js.save() to store JavaScript functions and db.eval() to execute them. However, this feature is deprecated in favor of aggregation pipelines and client-side logic.

Updated on: 2026-03-15T00:03:27+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements