Coding Journal

Jordan Vidrine

Daily Coding Journal

A Self-taught coder from the Cajun Prairie in rural Louisiana, currently working as a designer for Discourse.

I am always trying to better myself, and do so through learning new skills, trying out new routines, traveling, and pouring energy into hobbies. Since 2014, I have been recording, editing, and producing my own music under the name Skies Speak.

October 7th - React, Mongo, & Algorithms

Had a great weekend at the Google Developers Group Web Dev conference in Nola this weekend. Spent all day Saturday on the campus of Loyola hearing some great speakers and had to chance to meet a couple of new people as well. The speakers were great, as was the food, and it was all only $10!

After talking with a couple professional developers, it seems that my goal of starting with a remote gig is a bit lofty. Not that it CANT happen, moving forward my wife and I will be thinking of cities we may want to live for a couple of years for my to get some experience in person.

Today I’ll be continuing with the React course, getting into the Mongo course, and working through some Algorithms.

MongoDB

I covered a LOT of ground with mongoDB in the node course I completed over the summer. I liked it a lot so I wanted to take a course that’s sole focus was mongo. Im sure some of this will be repetitious, but I think it will solidify what I already know, as well as introduce me to some more advanced concepts.

To start, in this section we’ll be learning about Collections & Documents, Basic Data Types, and working with CRUD operations.

A database holds collections, which hold documents. These are created implicitly when you try and work with one. If it does not exist, it will be created in order for you to use it.

</br>

As noted in earlier exercises, to start up mongodb on my own computer (after install and config) I run this command: mondod --dbpath="path to the mongo data"

For most of this course, we will be working in the mongo shell as to not be specific to any driver/language. I am eager to work this way to get a better understanding of the underbelly of this database system.

The data in a mongoDB is stored as BSON data. BSON stands for BINARY JSON, for intents and purposes, it is JSON that is converted to BSON behind the scenes, and of course looks a lot like an object in javascript, with key value pairs.

The following would create a database named flights and insert a document into a collection name flightData.

use flights
db.flightData.insertOne({
  "departureAirport": "MUC",
  "arrivalAirport": "SFO",
  "aircraft": "Airbus A380",
  "distance": 12000,
  "intercontinental": true
})

To look at what is in your database, you can use db.flightData.find(). Adding pretty() chained to the .find() method will format the data in an easy to read way.

CRUD Operations

The following are some of the methods available to us to perform CRUD operations on our data.

Create: insertOne(data, options), insertMany(data,options)

Read: find(filter, options), findOne(filter, options)

Update: updateOne(filter, data, options), updateMany(filter, data, options), replaceOne(filter, data, options)

Delete: deleteOne(filter, options), deleteMany(filter, options)

This would delete the first document in the flightData collection that has a departure airport of “MSY” - db.flightData.deleteOne({departureAirport: "MSY"}) You could use any filter you wish to find and delete documents.

To Update some data, we can use the $set operator. It would look like this: db.flightData.updateOne({distance: 12000}, {$set: {marker:"delete"}}). What this would do is find the first document that matches the filter, then either update, or change the data identified as "marker".

Something like this would be useful to find all data with the marker “delete”, and delete only those from the database. It would look like this: db.flightData.deleteMany({marker:"delete"})

Understanding insertMany()

This, of course, allows you to insert many documents. To do so, you would pass an array of documents into the function, and the DB will create a document for each item passed in.

More on .find

There are lots of ways to use the .find() method to get the specific data you are looking for. There are also optional operators you can use to perform dynamic queries. The following will look for any documents that have data of distance greater than 1200: db.flightData.find({distance: {$gt: 1200}})

Another thing to understand is that .find() returns a “cursor,” not ALL of the data. It works this way because it would take too long to return a database with a lot of data. It returns it to us in batches, using “it” to go to the next batch.

Adding .toArray() to the find method will return an array of ALL the data, but this may not be beneficial.

Adding .forEach() to the find method will act similar to an array.forEach method. An example would look like this, using our shells printjson() function. db.passengerData.find().forEach((passenger) => {printjson(passenger)})

Using $ Operators

Be sure when updating to use $set in the object you pass to the update method. If you do not do this, you will change the document to be ONLY the updated object youre passing in.

Projection

In our database we may have a document like so : json { "name": "Jordan", "age": 32, "_id": ObjectId(234321456425sdfvgsdfg2345), "homeTown": "Eunice" } If on a website, I only want to render the Name and Age, I would still have to make a call to the database for the object, and then only pull out the data I want, theoretically wasting bandwith on info I will not be using.

We can get only what we want using projection. db.passengerData.find({}, {name: 1}). What this will do is return only the Name of each passenger (as well as their objectID by default). Putting a 1 in the key of the second object means ‘return this to me’. Setting it to 0 would let it know not to return it.

Embedded Documents & Arrays

It is possible to store documents nested into other documents. MongoDB allows up to 100 levels of nesting, and up to 16mb of data for a document. (its all text data, so this is alot).

It is also possible to store arrays inside of documents. These arrays can contain info like strings, or numbers, but they can also contain documents as well.

To access this structured data, we can use regular javascript syntax as we would if these were actual javascript objects. For instance, db.passengerData.findOne({name:"Jordan Vidrine"}).hobbies would return the info stored on the hobbies key.

To search with nested data we can do something like this : db.passengerData.find({"hobboirs"})

Algorithms & Data Structures

Continuing on with Big O Notation and Logarithms. A Logarithm is the inverse of exponentiation. For example, log2(8) = 3 means that 2 to the 3 power will equal 8 -> 23 = 8.

In another way, log2(value) = exponent –> 2exponent = value. The most common logs are binary, but there are also base10 and logE. For what we are concerned with Big O is the main picture, so when we refer to log, we will just say log.

Rule of thumb: The logarithm of a number roughly measures the number of times you can divide that number by 2 before you get a value that’s less than or equal to one.

Logarithmic Complexity

O(log n) is great! Check out its curve. The main point with all of this is to be able to see and understand what big O Expression can be related to an algorithm, and decide which would be best to use.

Certain searching algorithms have logarithmic time complexity. Efficient sorting algorithms involve it, as well as (sometimes) Recursion, which involves logarithmic space complexity.

Recap

Analyzing Performance of Arrays and Objects

In this section we will analyze what javascript already gives us with objects and array methods. We will compare and contrast runtimes for arrays, objects, and built-in methods, and understand all this through the lens of Big O.

Objects

Unordered, key value pairs. Duh! Objects work well when you don’t need order, and need fast access for insertion and removal.

Big O of Objects

Big O of Object Methods

Arrays

Arrays are ordered lists. Duh! There is an intrinsic ordering to the data in an array.

Big O of Arrays

Insertion

There are multiple ways to insert. Inserting at the end of the array is constant Big O time. There is no calculation needing to be done to add something to the end of the list, everything in the array remains the same, and something is added to the end.

To insert at the beginning however, requires more calculation. This will shift every element in the array over by however many items you are inserting (re-indexing), requiring a new position to be calculated for each item.

The same goes for removing at the beginning.

Big O of Array Mathods

Back to blog...