Executing MongoDB shell commands from Javascript file

29 / Jun / 2012 by Salil 3 comments

MongoDB uses javascript interface for the shell commands. We can really use this feature in a great way – by writing the MongoDB (shell) commands in a javascript (.js file) and execute in single go.

In this blog, I am going to show an example for the same:

[javascript]
print(‘===== My Demo Script =====’);
print(db.getCollectionNames()); // prints all collection names in respective database
print(db.myCollection.count()); // prints the count of myCollection collection.
[/javascript]

shell command to execute the script

[shell]
mongo 127.0.0.1/my-profile-db –username=’username’ –password=’pwd’ mongodb-script.js
[/shell]

mongodb-script.js is the shell script.
Basically this is just a regular mongodb connection command executing the script (after establishing successful connection).

In my next blog I will discuss an advance use-case – exporting collection records using shell script.

FOUND THIS USEFUL? SHARE IT

comments (3)

  1. winnie

    How can the connection be closed after the script has executed. Does it automatically close the connection(What happens if the script is scheduled to run periodically)?

    Reply
  2. Abhishek Kundu

    Very nice post. Can we also write an upgrade script using the Java Script file. I have a requirement where we had performed code re-factoring and there is a change in the Pojo’s structure. Could you please help me with some example to do so.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *