MAK
MAK

Reputation: 86

To write js from Server side in MongoDB

Can I write a procedure from server side which later on gets stored in Db and used for further transactions.

If yes can you provide me a sample code which shows how to write the js from server side in java.

Upvotes: 0

Views: 1510

Answers (3)

Sushant Gupta
Sushant Gupta

Reputation: 9458

Well you can use morphia. It is an ODM for mongo in Java. I know it is not like a PL/SQL kind of solution which you exactly want. But mongo has no extensive support for constraints or triggers as in Oracle or SQL Server. Validations and stuff needs to be done through code. ODM's like Morphia in Java, Mongoose in Node.js or Mongoengine in Python are pretty decent emerging libraries you can use for such tasks, but these constraints are on app side.

Upvotes: 0

Sammaye
Sammaye

Reputation: 43884

Can I write a procedure from server side which later on gets stored in Db and used for further transactions.

No but as @Philipp states you can write a block of JavaScript which will be evaled within the bult in JavaScript engine in MongoDB (spidermonkey atm unles you compile with V8).

I should be clear this IS NOT A STORED PROCEDURE AND IT DOES NOT RUN "SERVER SIDE" as SQL procedures do.

You must also note that the JS engine is single threaded and eval (when used) locks, and about a tonne of other problems.

Really the whole ability to store functions in the system collection is to store repeating code for tasks such as MR.

Upvotes: 2

Philipp
Philipp

Reputation: 69673

It is possible to do that, but 10gen advises that you shouldn't do it. Javascript functions can be stored in the special collections system.js and invoced through the eval command.

The rest of this post is copy&pasted from the official documentation: http://www.mongodb.org/display/DOCS/Server-side+Code+Execution#Server-sideCodeExecution-Storingfunctionsserverside


Note: we recommend not using server-side stored functions when possible. As these are code it is likely best to store them with the rest of your code in a version control system.

There is a special system collection called system.js that can store JavaScript functions to be reused. To store a function, you would do:

db.system.js.save( { _id : "foo" , value : function( x , y ){ return x + y; } } );

_id is the name of the function, and is unique per database. Once you do that, you can use foo from any JavaScript context (db.eval, $where, map/reduce) Here is an example from the shell:

> db.system.js.save({ "_id" : "echo", "value" : function(x){return x;} })
> db.eval("echo('test')")
test

See http://github.com/mongodb/mongo/tree/master/jstests/storefunc.js for a full example. In MongoDB 2.1 you will also be able to load all the scripts saved in db.system.js into the shell using db.loadServerScripts()

>db.loadServerScripts()
>echo(3)
3

Upvotes: 1

Related Questions