{ Introduction to MongoDB. }

Objectives:

By the end of this chapter, you should be able to:

  • Compare and contrast SQL and NoSQL databases
  • Install Mongo and start a Mongo Server
  • Perform CRUD operations in a Mongo console

Mongo Intro

So far we have been using an array to store our data. Since this array is being stored in memory on the server, it only lasts as long as our server is running. The second our server goes down, we lose all our data! This simply will not work for any practical application. At some point, we will need to be able to save, or persist, our data. To do that, we'll need to use a database.

NoSQL vs SQL

The database we will be using is MongoDB, which is a NoSQL database. To understand what that means, however, we first need to understand what a SQL database is. SQL databases store tables of data; and inside each table, the rows have essentially the same structure.

What does this mean? Let's consider a simple example. Suppose you have a simple blogging application, where users can log in and write posts. In a SQL database, this might mean you have two tables. The first table would be for users, and each row in the user table would contain data for that user, such as their email address, their name, and so on.

Similarly, the table of posts will have data on the posts. You'll probably want to store the text of the post, the date it was created, and so on. You'll also probably want to store a reference to the author who wrote the post.

In contrast with SQL databases which have tables, relationships between those tables and quite a few other properties, MongoDB is much less structured. The idea with MongoDB is that you can create objects with all different kinds of structures (we call these documents) and can store them inside of collections, which all exist in a database.

Install

Depending on your OS - here are instructions to install MongoDB.

Installing MongoDB on Mac OSX

For Windows, you can read how to install it here and here

Essential Terms

Now that we have MongoDB installed let's review some essential terms:

database - this is where all of our data is stored. We can create multiple databases, and each database will store multiple collections.
collection - collections are aggregations of objects (also known as documents). These documents can be of all shapes and sizes.
document - documents are objects that contain all types of information. They are represented as objects and can have keys and values of any type in JavaScript.

In the language of MongoDB, we wouldn't say that we have a table of data on users, where each row corresponds to one user. Instead we'd say that we have a collection of user documents, where each document corresponds to one user. The main difference with a NoSQL database like MongoDB is that these user documents don't need to have a common structure: one user could have an email address and a first name, another could have a last name and an address, and a third could have an entirely different set of data being stored.

CRUD

To perform CRUD operations in mongo, start up a mongo server by typing mongod in the terminal. Then open up a new tab and open up a mongo shell by typing mongo. We can see our databases by using show dbs and our collections in that database by using show collections. To connect to database simply type use NAME_OF_DATABASE

Read more about the commands here.

Create

To create in mongo we use the insert function, which belongs to a collection we are operating on. insert accepts an object of keys and values.

You can also insert an array of objects using the insertMany function.

db.users.insert({
    first: 'Elie'
    last: 'Schoppik',
    isInstructor: true,
    favoriteColors: ['Red', 'Blue', 'Purple'],
    favoriteFood: 'sushi'
});

db.users.insert({
    first: 'Mary',
    last: 'Malarkin',
    isInstructor: false,
    favoriteColors: ['Green', 'Yellow'],
    hometown: 'Omaha'
});

db.users.insertMany( [
     { first: "tim", fun_fact: 'owns a boat!' },
     { first: "matt", fun_fact: 'has a pet dog!' },
  ] );

Read

To read in mongo, we use the find command to find multiple objects and findOne for a single one

db.users.find()
/*
{
  "_id": ObjectId("58aa39cb62a53c60f58471c7"),
  "first": "Mary",
  "last": "Malarkin",
  "isInstructor": false,
  "favoriteColors": [
    "Green",
    "Yellow"
  ],
  "hometown": "Omaha"
}
{
  "_id": ObjectId("58aa39cc62a53c60f58471c8"),
  "first": "tim",
  "fun_fact": "owns a boat!"
}
{
  "_id": ObjectId("58aa39cc62a53c60f58471c9"),
  "first": "matt",
  "fun_fact": "has a pet dog!"
}
*/

db.users.findOne({first:'Mary'})
/*{
  "_id": ObjectId("58aa39cb62a53c60f58471c7"),
  "first": "Mary",
  "last": "Malarkin",
  "isInstructor": false,
  "favoriteColors": [
    "Green",
    "Yellow"
  ],
  "hometown": "Omaha"
}
*/

Update

To update documents in mongo, we use the update method and pass in different key-value pairs for the values we want to update. We can both update existing keys create new key-value pairs using this function.

db.users.update(
  // what to find the user by
   { first: "tim" },
   // what data to update
   {
      first: "Bob",
      moreInfo: "Is a new instructor",
      favorite_numbers: [11,12,13]
   }
)

/*
WriteResult({
  "nMatched": 1,
  "nUpserted": 0,
  "nModified": 1
})
*/

We can also use update to add a new document, if we pass it the upsert option! upsert is a portmanteau of update and insert. When you upsert into a collection, a document will be updated if it is found, and inserted if no matching document is found.

db.users.update(
   { name: "fjlsadkdfjsdaklfjdklsajfklds" },
   {
      name: "Upsert will insert if it can not find!",
      moreInfo: "How cool is that?",
      favorite_numbers: [11,12,13]
   },
   // if it is not found, insert it! (upsert = update or insert)
   { upsert: true }
)

/*
WriteResult({
  "nMatched": 0,
  "nUpserted": 1,
  "nModified": 0,
  "_id": ObjectId("58aa3a859c4f01de70dcd04b")
})
*/

Finally, if you want to update multiple documents, you can set multi equal to true.

// update every single one that is found using multi:true
db.users.update(
  // find all where the name is not equal to 'nope'
  { name: { $ne: 'nope' } },
  // set a new key of isHilarious to true
  {$set: { isHilarious: true }},
  // for more than 1 record
  { multi: true } 
)

/*
WriteResult({
  "nMatched": 4,
  "nUpserted": 0,
  "nModified": 4
})
*/

For more on update, check out the docs.

Delete

To delete documents in mongo, we use the remove method.

// remove a single user
db.users.remove({name:'Bob'})
/*
Removed 0 record(s) in 1ms
WriteResult({
  "nRemoved": 1
})
*/

// remove all the users
db.users.remove({})
/*
Removed 1 record(s) in 2ms
WriteResult({
  "nRemoved": 3
})
*/

Additional Find Methods

Since the process of deleting or updating involves first finding a record, we can use some built-in methods to perform both operations at once.

db.users.findAndModify({
    // find someone with a name of elie and a score greater than 10
    query: { name: "Elie", score: { $gt: 10 } },
    // increment their score by 1
    update: { $inc: { score: 1 } }
})

db.users.findOneAndUpdate(
   { name: "Elie" },
   { $inc: { "points" : 5 } }
)

db.users.findOneAndDelete(
   { "name" : "Elie" }
)

You can read more about the difference between modify and update here. And for documentation on all of these methods (and others we haven't discussed), go here.

When you're ready, move on to Introduction to Mongoose

Continue