How to create MongoDB stored procedure?


The following is the syntax to create MongoDB stored procedure −

db.system.js.save
(
   {
      _id:"yourStoredProcedueName",
      value:function(argument1,....N)
      {
         statement1,
         .
         .
         N
      }
   }
);

Now implement the above syntax. The query to create a stored procedure is as follows −

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

The following is the output −

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

Now you can call the stored procedure using eval(). The query is as follows −

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

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements