\chapter{Database based communication}

\section{What is MongoDB}
It is a database framework, we can use it to save user's data, including user account, chat history.

Why it? Because it's more simple than most of the traditional databases like SQL. And it's more compatible with JSON.

The good thing about this MongoDB is that you don't have to pre-define your data structure. Each item in your collection can have a different data structure. It gives you the flexibility to make a product prototype as quickly as possible.

\section{How to use MongoDB with Python}
\subsection{PyMongo}
'PyMongo\cite{pymongo}' is a python library for MongoDB. By using it, we could easily handle our database.

\subsection{Simple Example}
\lstinputlisting[language=Python]{data/codes/6/1pymongo_example.py}

In this example, first, we have defined a 'posts'. The 'posts' is a collection, or if you prefer, you can also treat it as a list.

Then we have defined two posts, they are dict object. We inserted two of them into the 'posts' collection.

Then we try to find one of the posts by using part of its data 'author == Mike'.

Then we added a new property for that post. The value of that property is a series of number 8.

Finally, we iterate the 'posts' collection to print out each post in that list.

\section{Why we have to use a database}
Why we have to use a database? It is because we want to save our user's data, including our user account itself persistently. You will not want your user found that his account was gone after the server computer has had a power loss. 

We can save all of our data on computer memory, but it's not practical for the following reasons:

\begin{enumerate}
    \item The computer memory, for a single computer, is limited. I have never heard of a computer's memory bigger than a computer disk space.
    \item When the computer shutdown, all of our data that was saved at the computer memory would be gone. That's not a good thing.
    \item You can, indeed, write your own script to handle the data processing. But soon you will find that what you wrote is so inefficient. Barely useable.
    \item In the convenience of sharing data across different systems. Also, convenient for backup your data.
\end{enumerate}