Learn how to create a JavaScript file that executes mongo shell commands
Why Mongo Shell Scripting ?
In the article: “Getting Started With the Mongo Shell – Basic CRUD Operations“, I covered the basics needed to perform CRUD operations on a MongoDB database, using the mongo shell. All of the examples in that article were in real-time. This is perfectly acceptable, and there may be cases in which you will want to perform administrative tasks manually. But it is also possible (and more likely) that you’ll want to create a script that executes a batch of mongo shell tasks. So, since JavaScript is the language used to interact with the mongo shell, we can pass a JS file to the mongo command in a terminal. This is mongo shell scripting.
This functionality offers a great deal of potential. For example, in this article I will provide a very simple demonstration that performs basic CRUD operations (“Create, Read, Update, Delete”).
An important note about the following examples:
If you want to run these examples locally, you have two options:
- Clone this GitHub repo and follow the instructions: https://github.com/kevinchisholm/mongo-shell-scripting-basic-crud-operations
- Scroll down to the section: “How to Demo“, and then follow the instructions
Creating a Database
Create the “madMen” database – Example # 1
1 2 3 |
//create the madMen database and connect to it var db = connect('127.0.0.1:27017/madMen'), allMadMen = null; |
In Example # 1, we create the “madMen” database and establish a connection to it. The “allMadMen” variable is set to null for now, but will indeed be used in the next example.
Adding Data to / Reading Data from a Database
Create the “names” collection – Example # 2
1 2 3 4 5 6 7 8 9 10 11 12 13 |
//create the names collection and add documents to it db.names.insert({'name' : 'Don Draper'}); db.names.insert({'name' : 'Peter Campbell'}); db.names.insert({'name' : 'Betty Draper'}); db.names.insert({'name' : 'Joan Harris'}); //set a reference to all documents in the database allMadMen = db.names.find(); //iterate the names collection and output each document while (allMadMen.hasNext()) { printjson(allMadMen.next()); } |
In Example # 2, we create the “names” collection and then add four documents to it. We then use the “allMadMen” variable to store a reference to the names collection, and then iterate it. The purpose of the iteration is to allow you to see in your terminal that the madMen database has actually been populated with documents. Example # 2 demonstrates both the “Create” part of our CRUD operations, and the “Read” part as well.
Updating A Collection Document
Let’s make a change to “Donald Draper” – Example # 3
1 2 3 4 5 6 7 |
//search for the document whose name property is: "Don Draper" db.names.find().forEach( function(thisDoc) { if(thisDoc.name === 'Don Draper'){ //update the record that contains "Donald Draper" and change it to "Dick Whitman" db.names.update( { "_id" : thisDoc._id }, { "name": "Dick Whitman" } ); }; }); |
Example # 3 is the “U” in our CRUD operation; in other words: “Update”. Here we use the forEach method of the names collection to iterate and find the document whose “name” property is set to: “Don Draper”. So, once we find that document, we update its “name” property to: “Dick Whitman”.
Deleting A Collection Document
Let’s delete “Dick Whitman.” – Example # 4
1 2 3 4 5 6 |
db.names.find().forEach( function(thisDoc) { if(thisDoc.name === 'Dick Whitman'){ //remove the record that contains "Dick Whitman" db.names.remove({ "_id" : thisDoc._id }); }; }); |
In Example # 4, we delete the document whose “name” property is set to: “Dick Whitman.”
Dropping a Database
Drop the “madMen” database – Example # 5
1 |
//drop the database |
db.dropDatabase();
In Example # 5, we drop the “madMen” database.
The Entire App – Example # 6A
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
//create the madMen database and connect to it var db = connect('127.0.0.1:27017/madMen'), allMadMen = null; print('* Database created'); //create the names collection and add documents to it db.names.insert({'name' : 'Don Draper'}); db.names.insert({'name' : 'Peter Campbell'}); db.names.insert({'name' : 'Betty Draper'}); db.names.insert({'name' : 'Joan Harris'}); print('* Documents created'); //set a reference to all documents in the database allMadMen = db.names.find(); print('* All documents:'); //iterate the names collection and output each document while (allMadMen.hasNext()) { printjson(allMadMen.next()); } //search for the document whose name property is: "Don Draper" db.names.find().forEach( function(thisDoc) { if(thisDoc.name === 'Don Draper'){ //update the record that contains "Donald Draper" and change it to "Dick Whitman" db.names.update( { "_id" : thisDoc._id }, { "name": "Dick Whitman" } ); print('* Updated document: ' + thisDoc._id); }; }); print('* All documents:'); //set a reference to all documents in the database allMadMen = db.names.find(); //iterate the names collection and output each document while (allMadMen.hasNext()) { printjson(allMadMen.next()); } db.names.find().forEach( function(thisDoc) { if(thisDoc.name === 'Dick Whitman'){ //remove the record that contains "Dick Whitman" db.names.remove({ "_id" : thisDoc._id }); print('* Removed document:'); //output the removed document as json printjson(thisDoc); }; }); print('* All documents ("Dick Whitman" removed):'); //set a reference to all documents in the database allMadMen = db.names.find(); //iterate the names collection and output each document while (allMadMen.hasNext()) { printjson(allMadMen.next()); } //drop the database db.dropDatabase(); print('* Database dropped'); |
In Example # 6A, we have the completed example code. To demonstrate, numerous print and printjson statements have been added so that the terminal output makes a bit more sense.
The Output – Example # 6B
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
MongoDB shell version: 2.6.5 connecting to: test connecting to: 127.0.0.1:27017/madMen * Database created * Documents created * All documents: { "_id" : ObjectId("550f2939a8a5d2643f6408fb"), "name" : "Don Draper" } { "_id" : ObjectId("550f2939a8a5d2643f6408fc"), "name" : "Peter Campbell" } { "_id" : ObjectId("550f2939a8a5d2643f6408fd"), "name" : "Betty Draper" } { "_id" : ObjectId("550f2939a8a5d2643f6408fe"), "name" : "Joan Harris" } * Updated document: 550f2939a8a5d2643f6408fb * All documents: { "_id" : ObjectId("550f2939a8a5d2643f6408fb"), "name" : "Dick Whitman" } { "_id" : ObjectId("550f2939a8a5d2643f6408fc"), "name" : "Peter Campbell" } { "_id" : ObjectId("550f2939a8a5d2643f6408fd"), "name" : "Betty Draper" } { "_id" : ObjectId("550f2939a8a5d2643f6408fe"), "name" : "Joan Harris" } * Removed document: { "_id" : ObjectId("550f2939a8a5d2643f6408fb"), "name" : "Dick Whitman" } * All documents ("Dick Whitman" removed): { "_id" : ObjectId("550f2939a8a5d2643f6408fc"), "name" : "Peter Campbell" } { "_id" : ObjectId("550f2939a8a5d2643f6408fd"), "name" : "Betty Draper" } { "_id" : ObjectId("550f2939a8a5d2643f6408fe"), "name" : "Joan Harris" } * Database dropped |
In Example # 6B, we have the terminal output from the code in Example # 6A.
How to Demo:
- Make sure the MongoDB database server is running
- Create a file named: “create-db.js”.
- Copy the entire contents of Example # 6 to “create-db.js”
- In a terminal window, execute the following command: “mongo create-db.js”
Summary
In summary, we learned how to perform basic CRUD operations on a MongoDB database by leveraging mongo shell scripting.
Helpful Links for Mongo Shell Scripting
Getting Started With the Mongo Shell – Basic CRUD Operations | Kevin Chisholm – Blog