Getting started with MongoDB

eyecatch

If you are looking for a Non-Structured Query Language(NoSQL) database with amazing performance for real time applications. MongoDB is a good choice. This post will bring you some information about it.

What is MongoDB?

MongoDB is a popular open-source NoSQL database that provides high performance, high availability, and easy scalability. It is designed to handle large volumes of unstructured data and is widely used in modern web applications, big data processing, and cloud-based applications.

Features

Document-oriented: MongoDB stores data in flexible, JSON-like documents (using BSON format), which makes it easy to store complex data structures. This schema-less nature allows for quick iterations and easy updates.
Scalability: MongoDB supports horizontal scaling through sharding, which divides large datasets across multiple distributed collections, allowing applications to scale easily as data grows.
High availability: It provides replication through replica sets, which consist of a primary node and multiple secondary nodes. In case the primary node fails, a secondary node is automatically promoted, ensuring high availability.
Rich query language: MongoDB offers a powerful query language that supports various types of queries, such as range queries, text searches, and aggregations, similar to SQL but with a more flexible syntax suited to JSON-like documents.
Indexing: MongoDB supports indexing on any field in a document, improving the speed and performance of read operations.
Aggregation framework: It includes a powerful aggregation framework that allows you to perform operations such as filtering, sorting, grouping, and transforming data, similar to the SQL GROUP BY and JOIN operations.
Flexible data model: The schema-less design allows you to store different types of data in the same collection without requiring a rigid schema, making it ideal for applications where data requirements evolve over time.
Community and ecosystem: MongoDB has a large, active community and a robust ecosystem of tools and libraries, including MongoDB Atlas (a fully managed cloud database service), MongoDB Compass (a GUI for MongoDB), and various drivers for different programming languages.

Use Cases

Real-time analytics and big data processing
Content management systems
Internet of Things (IoT) applications
Mobile apps and gaming
E-commerce platforms

NoSQL

MongoDB stores data as a document while traditional SQL DB as row in table. Saving and getting data with MongoDB is easier thanks to its structure. Let’s take a look at a sample. We have a Person entity and Book entity. The relationship is that a user can own many books.
With MongoDB we only need to save one single JSON for a user.

{
  "id": 1,
  "name": "Jonh",
  "books": [
      {
          "id": 1,
          "name": "A great book"
      },
      {
          "id": 2,
          "name": "A normal book"
      }
  ]
}

With traditional SQL DB we will need two tables for storing data like above.
Person table:

id name
1 John

Book table (“person_id” column references “id” column in Person table):

id name person_id
1 A great book 1
2 A normal book 1

Storing data with SQL DB looks more complicated but it makes sure the book with id “1” is not owned by anyone else other than a person with id “1”.

Installation and example

Installation and configuration

You can browse MongoDB server on this page .

mongodb download

For windows users: You can download the .msi package. The package includes the server and mongo compass GUI tool for interacting with the server.
For macOS users: Use brew command to install the server and compass tool.

brew tap mongodb/brew
brew install mongodb-community
brew services start mongodb-community
brew install --cask mongodb-compass

After installing, you can use the compass tool to connect to the MongoDB server.

mongodb connect

MongoDB username and password are not set by default. You must set administrator username and password in production mode.
I will create a demo database with a people collection.

mongodb create database

To add a user for editing, click on “Open MongoDB shell” and the below window will open.

mongodb create user

Compass will select the current open database for you. Use the command below to create a new user.

db.createUser({user: "userdemo", pwd: "password", roles: ["readWrite"]})

{ok: 1} means the command is executed successfully.

Application connect example

I will use NodeJS to connect to the MongoDB server and try to insert data. MongoDB supports many programming languages. You can check on the drivers website to download and install for your project.
Creating the project and adding dependencies.

npm init
npm install -S mongodb

or

yarn init
yarn add mongodb

Create an index.js file with below content. I will insert a person in the above example.

const { MongoClient } = require("mongodb");

const insertPerson = {
  id: 1,
  name: "John",
  books: [
    {
      id: 1,
      name: "A great book"
    },
    {
      id: 2,
      name: "A normal book"
    }
  ]
};

const uri = "mongodb://userdemo:password@localhost:27017/demo";

MongoClient.connect(uri).then((client) => {
  const db = client.db(); //db name is in connection string
  const peopleCollection = db.collection("people");
  peopleCollection.insertOne(insertPerson).then(() => {
    console.log("document is inserted!");
  }).catch((err) => {
    //ops, error occurred
    console.log(err);
  }).finally(() => {
    client.close();
  });
}).catch((err) => {
  console.log(err);
});  

mongodb nodejs insert

To run the code use the command below:

node index.js

If everything goes well, you will see inserted data in the compass window.

mongodb inserted data

_id is a generated field by mongoDB. It is used to identify unique records. You will need this field when updating records. There are a lot of functions that you can use. I only used the insertOne function. You can find more here .

Summary

MongoDB is a flexible, high performance, and scalable database, making it a go-to choice for many modern, data-driven applications. You can start developing your application first without worrying too much about data structure. Let’s give it a try to explore its features.
References:
MongoDB: The Developer Data Platform | MongoDB
NoSQL – Wikipedia
mongodb – npm (npmjs.com)

関連記事

カテゴリー:

ブログ

情シス求人

  1. チームメンバーで作字やってみた#1

ページ上部へ戻る