MongoDB query to execute stored function?


JavaScript function can be saved for reuse using a system collection called system.js. To store a function, use the db.collection.save(),

Let us first create a function. Following is the query −

> 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')")
WARNING: db.eval is deprecated

This will produce the following output −

The Name is: John

Updated on: 02-Apr-2020

480 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements