Basic Server Side Scripting in MongoDB

Posted by Darwin Biler on August 12, 2014

There might be times that you need to execute MongoDB commands via command line. One of the obvious reason for this is latency -- unlike hitting the MongoDB server across the network, executing the commands via shell is way very fast, specially if you are retrieving/processing huge amount of data.

Fortunately, MongoDB supports Server Side scripting, using JavaScript as programming language. It is as easy as creating a .js file in your server. In this tutorial, lets create a create_record.js file that will do the following tasks:

  • Connect to local MongoDB server
  • Create a database with name db1
  • Create a collection named "greetings"
  • Create a new record with the property "message" and value of "Hello World"
  • Print a status message

TO execute the file:

This will connect to localhost, in port 27017. Selecting the database "db1", then executing the create_record.js file.

That is how simple how to execute a JavaScript file in the server-side!


Did you find this useful?

I'm always happy to help! You can show your support and appreciation by Buying me a coffee (I love coffee!).