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
How to work with Stored JavaScript in MongoDB?
MongoDB allows you to store JavaScript functions in the system.js collection for reuse across database operations. These stored functions can be saved using db.system.js.save() and executed with db.eval().
Syntax
db.system.js.save({
_id: "functionName",
value: function (parameters) {
// Function logic here
return result;
}
});
Example: Creating a Stored Function
Let's create a function that formats a return message ?
db.system.js.save({
_id: "returnValue",
value: function (data) {
return 'The value==== ' + data;
}
});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Executing the Stored Function
Call the stored function using db.eval() ?
db.eval("returnValue(20)");
WARNING: db.eval is deprecated The value==== 20
Key Points
- The
_idfield serves as the function name for later reference. - The
valuefield contains the actual JavaScript function code. -
db.eval()is deprecated in newer MongoDB versions - consider using aggregation pipeline or application-level logic instead.
Conclusion
While MongoDB supports stored JavaScript functions through the system.js collection, db.eval() is deprecated. Modern applications should handle complex logic at the application level rather than storing JavaScript in the database.
Advertisements
