Chapter 3. Building a Flexible Database with MongoDB

A crucial step in building any web application is to choose the location for storing data. Databases are all the more critical for e-commerce applications. A database needs to be flexible enough to adapt to the ever-growing needs of the future while fitting the current products catalog. Scalability is another feature of paramount importance that can allow any business to grow or shrink. How many orders per minute does the application handle? What's the average response time of users' load peaks and valleys? How long does it take to find a product in a large pool? Will today's schema meet tomorrow's demands? These are a few of the many questions that affect the choice of database.

For around 40 years, relational database technologies (RDBMS) have governed the enterprise world. However, traditional databases often fall short in terms of scaling web applications to millions of users around the world. Today, leading internet companies (Amazon, Google, Facebook, and others) have developed NoSQL technologies to overcome the limitations of the RDBMS. NoSQL is focused on providing scalability, performance, and high availability. It has a growing number of test cases such as big data, big users, cloud computing, and the Internet of Things (IoT).

MongoDB is one of the most popular NoSQL databases. It has been adopted by a number of major websites such as Craigslist, eBay, Foursquare, The New York Times, and others. MongoDB provides a flexible data model and an expressive query language, and is highly scalable. We are going to use MongoDB to build our application. This chapter will get us started with Mongoose, which is a NodeJS driver for MongoDB. In further chapters, we are going to explore more advanced features to scale MongoDB. The following topics will be covered in this chapter:

  • Understanding MongoDB
  • CRUDing with Mongoose
  • Exploring the advanced features of Mongoose
  • Reviewing models and the server-side structure

Understanding MongoDB

MongoDB is an open source, cross-platform, document-oriented database. Instead of using the traditional table-based rigid schemas, MongoDB favors JSON-based documents with dynamic schemas.

MongoDB daemons and CLI

In the first chapter, we installed MongoDB. There are two main executables that come with the installation:

  • mongod: This is the database server and daemon
  • mongo: This is the database client and shell

Tip

The mongod server has to be running to use the mongo client.

Execute the mongo shell, and you will see the Command Prompt. It is similar to the NodeJS Command Prompt in the sense that it is a JavaScript environment. We can define custom JS functions apart from the core functions that are also available. For instance, the following Math module and parseInt are available:

mongo> db.products.insert({
...   title: 'Cellphone',
...   stock: parseInt(Math.random()*100),
...   price: Math.random()*100
... })
WriteResult({ "nInserted" : 1 })

Mapping SQL knowledge to MongoDB

For those of us who are already familiar with the SQL world, this section will be useful for translating this knowledge into the MongoDB way of performing similar actions.

Basics concepts

The following basic concepts and terms will help us speak the same language through this chapter:

SQL

MongoDB

Description

Column

Field

This is a label that represents a kind of data

Row

Document

This is the basic unit of data organized in columns/fields

Table

Collection

This is the collection of rows/documents and columns/fields

Database

Database

This is the group of tables/collections

Index

Index

This is the data structure to speed up queries

Table joins

Embedded docs

These are the link related rows/documents

Primary key

Primary key

This is the unique identifier of a row/column. Usually id or _id.

Queries

One of the advantages of MongoDB is its powerful querying language. Here are a few examples of common SQL queries and the way they translate to MongoDB:

SQL

MongoDB

Description

CREATE TABLE products (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  title TEXT,
  stock INTEGER,
  price REAL
);

(Implicit)

Creates a table/collection.

RDBMS needs the schema to be defined upfront whereas MongoDB does not. It has a flexible data storage that can change.

INSERT INTO products (title, stock, price) 
VALUES ('Product 1', 15, 112.36);
db.products.insert({
  title: 'Product1',
  stock: 15,
  price: 112.36
})

Creates a row/document.

SELECT * FROM products;
db.products.find()

Retrieves all data from the table/collection.

SELECT * FROM products
WHERE stock > 10 
AND stock < 100;
db.products.find({stock: {$lt: 100, $gt: 10}})

Finds all products where the stock is less than 100 and greater than 10.

UPDATE products
SET title = 'MEANshop';
db.products.update({},
  { $set: {title: 'MEANshop'} },
  { multi: true}
)

Updates a row/document from a table/collection.

DELETE FROM products;
db.products.remove({})

Deletes all data from the table/collection.

ALTER TABLE products
ADD last_update TIMESTAMP;

(Implicit)

SQL(ite): This adds a new column to the table.

MongoDB: These documents are schema-less so that new fields can be added at any time.

Being schema-less gives much flexibility, since we can add new fields without having to change the previous data.

Aggregators

Aggregators perform a calculation on the data, and usually reduce it to numeric values or filter/sort out data.

SQL

MongoDB

Description

SUM(column) / COUNT(*)
$sum

This sums/counts all rows/fields

WHERE / HAVING
$match

This filters documents based on the query passed

GROUP BY
$group

This groups rows/documents by an expression.

ORDER BY
$sort

This sorts the data

Examples

SELECT SUM(price)
FROM products AS total;
db.products.aggregate([{
  $group: {
    _id: null,
    total: { $sum: "$price" }
  }
}])

This adds the price of all products.

SELECT title, SUM(price) FROM products
GROUP BY title
HAVING title == 'Product';
db.products.aggregate([
  { $match: {title: 'Product' }},
  { $group: { _id: '$title', total: { $sum: "$price" } }}
])

This adds all products by title and shows only the one where the title is Product.

Tip

Try running these MongoDB code snippets on the mongo console, and verify the output.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.226.105