Getting Started With the Mongo Shell – Basic CRUD Operations

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/

Getting Started with Highcharts Part II: Formatting the Y Axis

Highcharts chartLearn how to properly format the “y” axis values of your Highcharts chart.

In “Getting Started with Highcharts Part I: Basic Charts,” we covered the absolute basics of how to use the Highcharts jQuery plugin. In that article, we demonstrated that with minimal effort, we can render a professional looking chart in our web page. The final example was a column chart that provided a data visualization of total 2014 sales in the Acme Widgets company.

But when you look at that final jsFiddle.net link, there are a few areas that could use additioal effort. The first area I wanted to focus on is the “y” axis (aka the “up and down” dimension of our chart.) We have properly labeled that axis “US Dollars,” but this approach is inefficient, and the actual dollar amounts are not formatted correctly.

Example # 1

In Example # 1, we have a column chart that is borrowed from the previous article in this series. The “y” axis is labeled as “US Dollars,” which is ok, but not very efficient. The actual numbers do not have dollar signs next to them, which minimizes the visual impact. Also, if we format these numbers correctly, we shouldn’t need to use the word “Dollar” in the label. Something like “Sales” would be more efficient and visually cleaner.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 1: http://jsfiddle.net/gf9d3pq4/1/

Example # 2

In Example # 2, we made two changes: 1) We simplified the label as: “Sales”, 2) We aded a “labels” property. This property is an object with one value: “format”. The value is a string which provides a template for how the “y” axis values should be formatted. In this case, we have added a dollar sign to the left of the number. This is great, but there is still one problem: the highest value on the “y” axis is “1100”. This number is not formatted correctly for most locals. Using the United States as an example, there should be a comma after the “1”. Let’s fix this.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 2: http://jsfiddle.net/gf9d3pq4/2/

How to Demo:

  • Click the jsfiddle link
  • Change the values of the “yAxis” property and then click the “Run” button in the upper-left-hand corner of the screen to see how your changes affect the appearance of the chart.

Example # 3

In Example # 3, we updated the labels.format value so that a comma is added for thousands. We also specified no decimal places. The comma is a big improvement, making four-digit numbers display correctly for the United States numbering syntax (proper syntax for other locals will vary).

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 3: http://jsfiddle.net/gf9d3pq4/3/

How to Demo:

  • Click the jsfiddle link
  • Change the values of the “yAxis” property and then click the “Run” button in the upper-left-hand corner of the screen to see how your changes affect the appearance of the chart.

Summary

In this article we learned how to format the “y” axis of a Highcharts chart. We discussed the “yAxis” property of the configuration object, the “labels” property, and how to add a dollar sign to properly convey US currency. We also demonstrated how to add a comma so that four-digit numbers are properly formatted.

Helpful Links for How to format the Highcharts “y” Axis

http://api.highcharts.com/highcharts#yAxis.labels

http://stackoverflow.com/questions/19810931/highcharts-y-axis-thousands-separator

Getting Started with Highcharts Part I: Basic Charts

Highcharts ChartLearn how to incorporate data visualization into your web page with just a few links of JavaScript

The data visualization trend shows no signs of slowing down, and charting is a key skill in that area. Highcharts is a jQuery plugin that provides a simple interface for creating great looking charts. There is a tremendous amount of muscle under the hood, which means that complex charts are not only within-reach, but they do not require a degree in advanced mathematics. If you want to use Highcharts for a personal or non-profit project, then it is available without cost under the Creative Commons Attribution-NonCommercial 3.0 License.

In this article, I will cover the absolute basics of Highcharts. I will keep the deeper features for a later post, and instead focus on the bare minimum needed to leverage this super-powerful jQuery plugin and quickly spin-up a chart on your web page.

Since Highcharts is a jQuery plugin, rendering a chart in your web-page could not be more simple:

That’s it! Of course this little snippet of code has no use because highcharts knows nothing about the chart that we want to create. As simple as this library is to use, you do need to provide a few details so that Highcharts knows what to do. There are plenty of defaults that are provided so that you can worry about only the most critical details, but at minimum, Highcharts needs the data that powers your chart.

Example # 1A

Example # 1B

In Example # 1A, we have the base HTML for the rest of the examples in this article. For the sake of brevity, I will not include the HTML in further examples, only the JavaScript. Just keep in mind that the JS in the rest of the examples will go where you see the comment: “highcharts code will go here.”

In Example # 1B, we have the bare-minimum JavaScript needed to invoke the highcharts jQuery plugin. We passed an object to the highcharts method, which contains a “series” property. The value of this property is an array. There are multiple options when it comes to this series property, for now we will keep things very simple; the array has one element and that element is an object. This object has a “data” property whose value is an array. The element of that array has numbers. The numbers in that array are the key to your chart.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 1B: http://jsfiddle.net/u4wke4vo/1/

How to Demo:

  • Click the jsfiddle link
  • Change the data in the “series” property’s array and then click the “Run” button in the upper-left-hand corner of the screen to see how your changes affect the appearance of the chart.

X and Y Axis

It might be a good idea to take a moment to discuss the concept of the x and y axis. Although this article is focused on the absolute basics of Highcharts, there is little to accomplish here without a firm understanding of how data is represented visually. The “x” axis represents the horizontal dimension of the chart, and the “y” axis represents the vertical dimension. Another way of looking at this is: the “x” axis is the “left to right”, and the “y” axis is the “up and down”.

When you look at the jsfiddle link for Example # 1B, you’ll notice that the “x” axis doesn’t really offer too much value. What do the numbers 150, 900, 675 and 400 mean when they are mapped to an “x” axis of 0 to 3? For this article, I am using a “Total Sales” context so that each example will present the total sales for a group of three representatives of the Acme Widget Company. The “x” axis is the sales reps. So instead of displaying arbitrary numbers, the “left to right” dimension of our chart will display names of the sales reps.

Example # 2

In Example # 2, we’ve added a second property to the configuration object named “xAxis.” The xAxis property is an array of strings. Each string provides a label for the “x” axis. In our case, that “left to right” dimension of the chart represents the Acme Widge company’s sales representatives.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 2: http://jsfiddle.net/u4wke4vo/2/

How to Demo:

  • Click the jsfiddle link
  • Change the data in the “series” property’s array and then click the “Run” button in the upper-left-hand corner of the screen to see how your changes affect the appearance of the chart.

Notice that Example # 2 is a line chart. That is the default chart type that Highcharts presents when you do not provide enough specifics. It looks nice, but it does not make a great deal of sense in this context because visually, it gives the impression of “data over time”. Our “Total Sales” context represents a series of set values for a year, so we need a chart type that better represents that kind of thought process. In my opinion, a column chart is a perfect example.
Example # 3

We’ve added a new property to the configuration object called “chart”, which is an object. This object has one property: “type”. This is where you tell Highcharts whether you want a “pie” chart, a “bar” chart, or a “line” chart, etc. For our examples, a “column” chart makes much more sense than a line chart.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 3: http://jsfiddle.net/u4wke4vo/3/

How to Demo:

  • Click the jsfiddle link
  • Change the data in the “series” property’s array and then click the “Run” button in the upper-left-hand corner of the screen to see how your changes affect the appearance of the chart.

You may have noticed that the chart’s title is: “Chart Title”, the “y” axis label is: “Values” and the “x” axis label is: “Series 1.” These are defaults that Highcharts provides when you have not specified them. While a helpful feature, it is likely that you’ll want to specify those kinds of labels. Let’s take care of that now.

Example # 4

We’ve changed a few things in Example # 4. The “title” and “subtitle” properties are self-explanatory. The “yAxis” property is an object, whose “title” property is yet another object with a “text” property. This determines the label for the “up and down” dimension of our chart. The sole object in the “series” property’s array now has a “name” property. This provides the label for the “x” axis, or “left to right” dimension of our chart. In this case, it indicates that all sales figures represent sales in the United States only.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 4: http://jsfiddle.net/u4wke4vo/4/

How to Demo:

  • Click the jsfiddle link
  • Change the values of the various properties and then click the “Run” button in the upper-left-hand corner of the screen to see how your changes affect the appearance of the chart.

Summary

In this article, I covered the bare-minimum needed to render a Highcharts chart in your web page. We covered the simple syntax for instantiating the jQuery plugin, and how to pass-in the configuration object. We also covered how to provide data, the x and y axis, and how to label them. We also discussed how to specify the type of chart that should be rendered.

Helpful Links for getting started with HighCharts

http://www.highcharts.com/

http://www.highcharts.com/docs

http://www.highcharts.com/demo

Renaming a file with Node.js

Node.js LogoLearn how to rename a file with Node.js, in ten lines of code

I was fleshing out a few ideas on a project today and found myself trying to figure out how to rename a file with Node.js. I have no doubt that there are better ways to go about this, but I thought I’d document my findings.

The first thing I realized is that the low-level nature of Node.js offers a great deal of power, but also with that power comes a the need to handle all of the details. For me, this meant getting references to four things:

  1. The name of the old file
  2. The name of the new file
  3. The full path to the old file
  4. The full path to the new file (which does not exist yet)

The first two items are easy: I just had to provide a name for the old file, and decide what to call the new file. The last two items involved a bit more effort. I needed to do do three things:

  1. Get the path of the folder that contains the old file
  2. Add a trailing slash to that path
  3. Set a permanent reference to the old file

To accomplish all of these tasks, I decided to use the filepath Node.js module.

Example # 1A

 Example # 1B

Example # 1A shows the contents of package.json. There is only one dependency: the filepath Node.js module.

In Example # 1B, I first set references to the file system module, as well as the filepath module. Next, I provided strings for the names of the old and new files. The filepath module is then used to get the path to the current folder; I set that to the fpFolder variable (adding a trailing slash to that string, which will be needed when we append file names to that string).

The variable fpFile is used as a permanent reference to the old file (this will come in handy for Example # 3.) Finally, I build the full file paths for the old and new files. After that, a couple of console.log statements to make sure all of this work is correct.

Example # 1C

Example # 1C shows the output of the two console.log statements. Each path will vary for you a bit, so I simply put “[YOUR LOCAL PATH TO]” for the folder structure that leads up to that file in the github repo that you cloned (see “How to Demo” below).

This example does not actually rename a file. So, now I will use the file system module to make that change.

How to Demo:

  • Clone this github repo: https://github.com/kevinchisholm/video-code-examples
  • Navigate to: JavaScript/node-js/node-modules/fs/fs-rename
  • Execute the following command in a terminal prompt: npm install
  • Execute the following command in a terminal prompt: node filepath-1.js

Example # 2

In Example # 2, I use the file system module’s rename method to rename the file: “re-name-me.txt.” This method takes two arguments: a path to the old file, a path to the new file and a callback. The callback takes one argument: an error object. Inside of the callback, I check for the error object, and then output the path of the new file. Follow the instructions below to see this code in action. After you execute the code, the file: “re-name-me.txt” will be renamed to: “ive-been-renamed.txt.”

In order to rename Example # 2 again, you’ll need to manually rename the file: “ive-been-renamed.txt” back to: “re-name-me.txt”. After a few times back and forth, this got pretty tedious and I started to think that there must be a way to toggle the file back and forth. Meaning: If the file has been renamed, change it back to the original name, and so forth.

How to Demo:

  • Clone this github repo: https://github.com/kevinchisholm/video-code-examples
  • Navigate to: JavaScript/node-js/node-modules/fs/fs-rename
  • Execute the following command in a terminal prompt: npm install
  • Execute the following command in a terminal prompt: node filepath-2.js

Example # 3A

In Example # 3A, I use the ternary operator when setting the final path for the old and new files. In each case, I check to see if the old file exists, and then depending on the answer, I set each path accordingly.

Example # 3B

Example # 3B is the full code for the final version of this file. I combined all var statements and cleaned up the code a bit. When you follow the instructions below, you’ll see that you can keep executing node filepath-2.js over and over, and the text file will toggle between the old name and the new name.

How to Demo:

  • Clone this github repo: https://github.com/kevinchisholm/video-code-examples
  • Navigate to: JavaScript/node-js/node-modules/fs/fs-rename
  • Execute the following command in a terminal prompt: npm install
  • Execute the following command in a terminal prompt: node filepath-2.js

Summary

As I mentioned, there are probably a number of ways to do this that are more efficient. Everything I detailed here was the result of a few minutes with Google. Hopefully this article either got you where you needed to go, or pointed you in the right direction.

Helpful Links for Renaming a File with Node.js

http://nodejs.org/api/fs.html

https://www.npmjs.com/package/filepath

Getting started with the filepath Node.js module

Node.js LogoWhen you need to reference and work with the local file system in your Node.js program, the filepath module is quite a handy tool.

Even if your Node.js program is a web-server of some sort, working with the local file system is somewhat inevitable. While Node.js does provide low-level file system access (see the Node.js fs module), abstraction is always helpful, particularly when dealing with absolute paths.

The filepath Node.js module is a very helpful utility for simple access to file paths. You’ll need only a package.json file with this module as a dependency, an “npm install” command, and then you are up and running. This article provides a quick introduction to a few of the most common methods.

Example # 1A

Example # 1B:

In Example # 1, we first create the FP variable, which references the filepath module. Then we create the path variable, which holds the return value of the FP object’s newPath method. And finally, we output the path in the console. Example # 1B shows the terminal output when we use console.log to view the path variable. This path will vary for each user so I simply put “[YOUR LOCAL PATH TO]” for the folder structure that leads up to that file in the github repo that you cloned (see “How to Demo” below).

How to Demo:

  1. Clone this github repo: https://github.com/kevinchisholm/video-code-examples
  2. Navigate to: JavaScript/node-js/filepath
  3. Execute the following command in a terminal prompt: node filepath-1.js

Example # 2

Example # 2 demonstrates the list method. The only real difference between this code and Example # 1, is the new variable “files”, which receives the value of the list method, when called on our path variable. The files variable ends up as an array. Each element in the array is an object whose “path” property is a string that points to a file in the current directory.

How to Demo:

  1. Clone this github repo: https://github.com/kevinchisholm/video-code-examples
  2. Navigate to: JavaScript/node-js/filepath
  3. Execute the following command in a terminal prompt: node filepath-2.js

Example # 3A

Example # 3B

Example # 3C

Example # 3D

In Example # 3A, we see the recurse method in action. Just as the name implies, the recurse method will recursively list all of the files in the current directory. As a result, if one of those files is a folder, then it will list all of the files in that folder, and so on. This method differs from the previous two examples in that it takes a callback. The callback is a bit like a forEach call; it iterates over all of the files or folders in the path, and calls the callback for each one. Inside of the callback, the path variable is the current path being iterated over.

Example # 3C is the output from the code in Example # 3A.

In Example # 3C, we use the toString() method of the path object so that instead of a bunch of objects that we would need to handle, we just get the values we are after; the string representation of the path to that file or folder.

Example # 3D is the output from the code in Example # 3C.

How to Demo:

  1. Clone this github repo: https://github.com/kevinchisholm/video-code-examples
  2. Navigate to: JavaScript/node-js/filepath
  3. Execute the following command in a terminal prompt: node filepath-3.js

Summary

The filepath Node.js module has much more to offer than was demonstrated here. Hopefully, this article has demonstrated how easy it is to get started with filepath.

Helpful Links for the filepath Node.js module

https://www.npmjs.com/package/filepath

http://nodejs.org/api/fs.html