Quick start with MongoDB

What is MongoDB?

MongoDB is a document-oriented database, not a relational one. MySQL is a relational database. A relational database relies on the concept of rows. A document-oriented database relies on documents.

This type of structure is designed to scale because it allows embedded documents and arrays. It also fits the object-oriented developer mindset better. MongoDB doesn’t have predefined schemas like MySQL does. Without fixed sizes or types, it is a lot easier to experiment with models in order to choose the one that suits our needs.

 

Documents

At the heart of MongoDB is the document. A document is an ordered set of keys associated with values. The representation might differ depending on the programming language, but for Javascript, documents are represented as objects:

{"fruit": "banana"}

This document has a key fruit and a value banana. Of course documents can contain a lot a diffent key/value pairs:

{"title": "Quick Start MongoDB", "views": 4}

Note: documents are type-sensitive and case-sensitive. “views” is different than “Views”, 5 is different than “5”.

 

Collections

A collection is a group of documents. If you are familiar with MySQL, think of a document as row, and think of a collection as a table. Collections have dynamic schemas. This means that documents inside the same collection can have different keys, value types and number of keys. So these two documents:

{ "fruit": "apple", "isRotten": false}

{ "animal": "Monkey", "name": "Joe", "age": 8}

can be part of the same collection.

Collections are identified by a name ( UTF-8 string )

 

Databases

Finally, collections are grouped inside of a database. A single instance of MongoDB can hold several databases, each grouping zero or more collections. Each database is stored on a separate file on disk. Because of this, there are some restrictions on the name you can give a database. admin, local, config are reserved names.

You can concatenate a database name with a collection name in order to get a namespace. For example, if you use the database blog and you have a collection called posts. The namespace of that collection would be blog.posts

 

Getting Started

Let’s get our hands dirty! First, download MongoDB here : https://www.mongodb.com/download-center#community. Decompress, follow the instructions, go to your terminal, and run mongod to start the server. ( or mongod.exe on windows ). You’ll start seeing some version and system info. MongoDB now listens to connection on port 27017 by default. MongoDB comes with a Javascript shell that allows us to interact with a MongoDB instance from the command line. In a new terminal window, run mongo.You should see:

MongoDB shell version: x.x.x

connecting to: test

The shell is a full-featured Javascript Interpreter. You can run some basic math, use the standard Javascript methods ( map, replace, filter … )  and write functions. You can write multiline commands. The shell will detect if the statement is complete or not and allow you to continue on the next line. Press Enter three times to quit a multiline command typing.

So, doing Javascript in the shell is cool, but the interesting thing is that you have a standalone MongoDB client. On startup, the shell connects you to a database and assign it to the variable db. In the example above, the MongoDB server connected to the database test. You can see which database you are currently connected to:

 > db
 test

You can run use to select which database to use:

 > use myAwesomeDB
 switched to db myAwesomeDB
 > db
 myAwesomeDB

 

Create, Read, Update, Delete

 

Let’s manipulate some data in the shell. We will assume that we have a bookstore and we will use the shell to manipulate the data about our books. Our store needs at least a book, let’s add one. We will create a variable called firstBook and give it some values:

firstBook = {"title": "1984", "author": "George Orwell", "year": 1949 }

We give it a title, an author and a publishing year. Now, we need to insert it into our database.  To do this, we will use the insertOne method.

>use bookStore
switched to db bookStore
>db.books.insertOne(firstBook)
{       
   "acknowledged" : true,
   "insertedId" : ObjectId("5952ccd3e1ebf5f25a2fd0e1")
}

 

Remember that the current database you are using is assigned to the global variable db. As you can see, we insert our new book into the books collection. In this case, db.books means that our namespace is bookStore.books.

To see our book in our database, we can use the find method.

>db.books.find()
{ "_id" : ObjectId("5952ccd3e1ebf5f25a2fd0e1"), "title" : "1984", "author" : "George Orwell", "year" : 1949 }

Let’s add another book for fun:

> secondBook = {"title": "The Alchemist", "author": "Paulo Coehlo", "year": 1988}
{ "title" : "The Alchemist", "author" : "Paulo Coehlo", "year" : 1988 }
> db.books.insertOne(secondBook)
{
        "acknowledged" : true,
        "insertedId" : ObjectId("5952cf18e1ebf5f25a2fd0e2")
}
> db.books.find()
{ "_id" : ObjectId("5952ccd3e1ebf5f25a2fd0e1"), "title" : "1984", "author" : "George Orwell", "year" : 1949 }
{ "_id" : ObjectId("5952cf18e1ebf5f25a2fd0e2"), "title" : "The Alchemist", "author" : "Paulo Coehlo", "year" : 1988 }

 

To read our collection, we already used the find method. If we only want to find one document, we can use findOne:

> db.books.findOne()
{
        "_id" : ObjectId("5952ccd3e1ebf5f25a2fd0e1"),
        "title" : "1984",
        "author" : "George Orwell",
        "year" : 1949
}

 

You can also pass a query to find and findOne in order to restrict your search. For example:

> db.books.find({"title": "The Alchemist"})
{ "_id" : ObjectId("5952cf18e1ebf5f25a2fd0e2"), "title" : "The Alchemist", "author" : "Paulo Coehlo", "year" : 1988 }

Of course, find will return every document that matches the query, findOne will only return the first one it finds.

Let’s move on to updating a document. If we want to modify one of our book, we can use updateOne. This method takes at least two parameters: the first one is the critera to find the document you want to changed, the second is the change you want to apply to that document. For example, let’s change the published year of The Alchemist from 1988 to 1995.

> db.books.updateOne({"title": "The Alchemist"}, {$set: {"year": 1995} })
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
> db.books.find()
{ "_id" : ObjectId("5952ccd3e1ebf5f25a2fd0e1"), "title" : "1984", "author" : "George Orwell", "year" : 1949 }
{ "_id" : ObjectId("5952cf18e1ebf5f25a2fd0e2"), "title" : "The Alchemist", "author" : "Paulo Coehlo", "year" : 1995 }

The first argument of updateOne is {“title”: “The Alchemist”}. This allows us to find the document we want to change. In our case, because our database only contains two books, we could have used {“author”: “Paulo Coehlo”} or {“year”:  1988}. Those two queries would have returned the same document.

The second argument use the $set operator to update our document. When we read our database with find again, the year is not 1988 but 1995 !

Finally, in order to delete a document, you can use deleteOne.  You give it a filter argument and it will delete the document that matches the filter:

> db.books.deleteOne({"title": "The Alchemist"})
{ "acknowledged" : true, "deletedCount" : 1 }
> db.books.find()
{ "_id" : ObjectId("5952ccd3e1ebf5f25a2fd0e1"), "title" : "1984", "author" : "George Orwell", "year" : 1949 }

If you want to delete several documents, you can use the deleteMany method. I works like deleteOne, you give it a filter argument and it will delete every single document that matches the filter.

So, now you know how to CRUD ( Create, Read, Update, Delete ). I hope this first article was clear and simple. The shell really allows you to play with MongoDB and its methods. You can try and get more familiar with those basic but powerful methods.

In the next article, we will touch on data types in MongoDB.

Feel free to share and comment!

Have a nice day.

2 Comments, RSS

  1. […] To get up and running with MongoDB, check out this article […]

  2. […] Note: I will be using the MongoDB shell in my terminal to show some examples. If you do not have it installed, please refer to my Quick start with MongoDB article […]

Your email address will not be published. Required fields are marked *

*