Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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.jscollection with an_idandvaluefield.
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.
Advertisements
