How to work with Stored JavaScript in MongoDB?

MongoDBDatabaseBig Data Analytics

It is saved in the special system.js collection. For this, use db.system.js.save(). Following is the syntax −

db.system.js.save({
   _id: "anyFunctionName",
   value: function (returnValue) {
      return ‘yourMessage ' + returnValue;
   }
})

Let us implement the above syntax. Following is the query −

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

Following is the query to call the above function to print the actual data −

> db.eval("returnValue(20)")
WARNING: db.eval is deprecated

This will produce the following output −

The value==== 20
raja
Published on 13-May-2020 13:09:11
Advertisements