Getting Started with Mongo Shell Scripting – Basic CRUD Operations

MongoDB

mongoDB Logo - mongo shell scriptingLearn 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:

  1. Clone this GitHub repo and follow the instructions: https://github.com/kevinchisholm/mongo-shell-scripting-basic-crud-operations 
  2. Scroll down to the section: “How to Demo“, and then follow the instructions

Creating a Database

Create the “madMen” database – Example # 1

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

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

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

In Example # 4, we delete the document whose “name” property is set to: “Dick Whitman.

Dropping a Database

Drop the “madMen” database – Example # 5

db.dropDatabase();

In Example # 5, we drop the “madMen” database.

The Entire App – Example # 6A

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

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

http://docs.mongodb.org/manual/administration/scripting/

Getting Started With the Mongo Shell – Basic CRUD Operations

MongoDB

mongoDB logoLearn how to perform CRUD operations on a MongoDB database, using the mongo shell

While it is likely that you will want to leverage MongoDB for your Node.js application, the mongo shell is an incredibly useful administrative tool that should not be overlooked. The definition provided by mongodb.org is: “The mongo shell is an interactive JavaScript shell for MongoDB, and is part of all MongoDB distributions.” It really is that straightforward: you can interact with your MongoDB database using JavaScript, in a command shell. Brilliant.

In this article I will demonstrate how to create a MongoDB database, add documents to the database, update a document, delete a document, and then delete your database. All of this will be done using a command prompt and JavaScript.

NOTE: I assume that you already have MongoDB installed globally. If you do not have MongoDB installed and need assistance with that, please see the “Installation Links” section at the end of this article.

Starting the Mongo shell

Before you can interact with a MongoDB database using the mongo shell, you’ll need to have the MongoDB database server running. In order to start the MongoDB server, execute: “mongod” in your terminal window. The output you see should be similar to this:

Starting the Mongo shell couldn’t be easier. Open a second terminal window, and then execute the command: “mongo”. You should see the following output in your terminal window:

You may be surprised to see that you are connected to “test”, but that is the default database. In order to see a list of existing databases, execute the following command:

You should see the following output in your terminal window:

Creating a MongoDB Database

In order to create a new database, use the “use” command. Execute the following command:

You should see the following output in your terminal window:

Now take a look at the existing databases again by executing the command: “show dbs”. You may be wondering why the new database “madMen” does not show up in the list of existing databases. This is because it has no data. Let’s add some data to that database.

Adding Documents to a Collection

With MongoDB, we can create collections on the fly when we add data. For example, the new database “madMen” is empty. We can add a “names” collection and insert a document into that collection all in one command.

Execute this command:

You should see the following output in your terminal:

Now, let’s take another look at the list of databases. Execute the command: “show dbs”.

You should see the following output in your terminal:

The reason you now see the madMen database in the list is because it contains some data. Let’s add three more documents to the “names” collection. Execute the following commands:

If you executed the previous JavaScript, the “names” collection should now have four documents. Let’s talk about how you can view all the documents in a collection.

Iterating Over the Documents in a Collection

If you want to view all of the documents in a collection, using the mongo shell, it is at minimum, a two-step process. First, obtain a reference to the collection, and then iterate over the collection using the next() method. In the following example, we’ll create a while loop. The hasNext() method will be used as the condition of the loop, and then inside of the loop, we’ll use the next() method to get the “next” document in the collection. The return value of that method will be passed to the printJson function, which is specific to mongo.

Execute this code:

In the previous example, we set the variable “allRecords” equal to the result of “db.names.find()”. The “allRecords” variable then has a reference to all of the documents in the “names” collection. We then use a while loop to iterate over the collection. On each iteration, the next method of the allRecords variable is passed to the printjson function. The output in your terminal should be similar to this:

The values of each document’s “_id” property will differ in your terminal because these are unique IDs, generated by the instance of MongoDB. The rest of the data should be the same.

Updating a Document

Now that we have four documents in the “names” collection, let’s update one of those documents. We do this by using the “save” method of the collection object. We’ll need to pass the “_id” of the document that we want to update, as well as the new data. Let’s change “Don Draper” to “Dick Whitman”.

You should see the following output in your terminal:

Now, let’s use the while loop we created earlier to inspect all records of the “names” collection:

You should see the following output in your terminal:

As you can see, the document that contained “Don Draper” has now been changed to “Dick Whitman”.

Deleting a Document

Let’s delete the same document that we just updated. In order to do that, we’ll use the “remove” method of the collection object, passing it the “_id” of the exact document that we want to delete:

You should see the following output in your terminal:

Now let’s take a look at all the documents in the database again:

As you can see, the document that we deleted no longer exists.

Deleting a Database

While not something you are likely to do too often, deleting a database is a perfectly valid MongoDB operation. The syntax could not be more simple; use the “dropDatabase” method of the db object.

You should see the following output in your terminal:

Now, execute the command: “show dbs”. You should see the following output in your terminal:

 Summary

In this article, we learned about basic CRUD operations in Mongo Shell. We learned how to start the database server, start the shell and view a list of all databases. We also covered steps needed to create a database, add documents to that database, update a document, delete a document and delete a database. There is a mountain of topics when it comes to the Mongo Shell. I hope this article helped you in getting started.

Helpful Links for the mongo shell

General Links

http://www.mongodb.org/

http://try.mongodb.org/

http://docs.mongodb.org/manual/crud/

http://docs.mongodb.org/v2.2/mongo/

http://www.tutorialspoint.com/mongodb/

Installation Links

Install MongoDB on OS X — MongoDB Manual 3.0.1
http://docs.mongodb.org/manual/tutorial/install-mongodb-on-os-x/

Install MongoDB on Windows — MongoDB Manual 3.0.1
http://docs.mongodb.org/manual/tutorial/install-mongodb-on-windows/

Install on Linux — MongoDB Manual 3.0.1
http://docs.mongodb.org/manual/administration/install-on-linux/