Serengeti logo BLACK white bg w slogan
Menu

Getting started with MongoDB

Abhijeet Koli, Lead Software Developer
06.10.2023.

MongoDB is a popular NoSQL database that offers flexibility, scalability and powerful data manipulation capabilities. In this blog post, we will explore the fundamental concepts of MongoDB, including creating database, collections, establishing relationships and performing various types of aggregations.

Setting Up a Docker Environment

Set up the docker environment using steps in the previous blog post.

Create a docker-compose.yml

version: '3.9'
  networks:
    localnet:
      attachable: true
  services:   
     
    mongo1:
      image: "mongo:4.0-xenial"
      container_name: mongo1
      command: --replSet rs0 --smallfiles --oplogSize 128
      volumes:
        - rs1:/data/db
        - ./mongo/init_script:/init_script
      networks:
        - localnet
      ports:
        - "27017:27017"

    mongo2:
      image: "mongo:4.0-xenial"
      container_name: mongo2
      command: --replSet rs0 --smallfiles --oplogSize 128
      volumes:
        - rs2:/data/db
      networks:
        - localnet
      ports:
        - "27018:27017"

    mongo3:
      image: "mongo:4.0-xenial"
      container_name: mongo3
      command: --replSet rs0 --smallfiles --oplogSize 128
      volumes:
        - rs3:/data/db
      networks:
        - localnet
      ports:
        - "27019:27017"
     
  volumes:     
      rs1:
      rs2:
      rs3:     

Update the hosts file

Open c:\windows\system32\drivers\etc\hosts file in any editor as administrator. Add this line at the end and save the file.

127.0.0.1   mongo1 mongo2 mongo3

Create MongoDB Containers

$ docker-compose up -d
Creating network "mogondb_localnet" with the default driver
Creating volume "mogondb_rs1" with default driver
Creating volume "mogondb_rs2" with default driver
Creating volume "mogondb_rs3" with default driver
Creating mongo2 ... done
Creating mongo1 ... done
Creating mongo3 ... done

Connect to MongoDB

$ sudo docker exec -it mongo1 mongo

Creating a MongoDB Database

To create a MongoDB database, use the use command in the MongoDB shell.

> use FoodMarket
switched to db FoodMarket

Creating Collections

Collections in MongoDB are like tables in relational database. You can create a collection by simply inserting a document into it. MongoDB will create the collection if it does not exist.

> db.products.insertOne({
    title: "Kruška Abata"
    supplier: "Enna Fruit"
})

Establishing Relationships

MongoDB supports several ways to model relationships between data. The two most common methods are embedding and referencing.

Embedding

Embedding involves nesting related data within a document. In our example, a product collection document may contain an array of rates.

> db.products.insertOne({
    title: "Kruška Abata",
    supplier: "Enna Fruit",
    rates: [
      {
        quantity: 1
        unit: "kg"
        price: 1.69
      },
      {
        quantity: 2
        unit: "kg"
        price: 3.00
      },
    ]   

})

Referencing

Referencing involves storing references to the related document's object ID.

> db.rates.insertOne({
    title: "Kruška Abata",
    rates: [
      {
        productId: ObjextId("507f1f77bcf86cd799439011")
        quantity: 1
        unit: "kg"
        price: 1.69
      },
      {
        productId: ObjextId("507f1f77bcf86cd799439022")
        quantity: 2
        quantity: 1
        unit: "kg"
        price: 3.00
      },
    ]   
})

Aggregations

MongoDB provides a powerful set of aggregations for data transformation and analysis. We can count the number of products by each supplier.

Grouping Data

$ db.products.aggregate([
  {
    $group: {
      _id: "$supplier",
      totalProducts: { $sum: 1}
    }
  }
])

Filtering Data

We can filter the database according to criteria.

$ db.products.aggregate([
  {
    $match: {
      supplier: "Enna Fruit"
    }
  }
])

Sorting Data

We can sort data in ascending or descending order.

$ db.products.aggregate([
  {
    $sort: {
      title: -1
    }
  }
])

Joining Data

Use the $lookup state to perform left outer joins between collections.

$ db.products.aggregate([
  {
    $lookup: {
      from: "rates",
      localField: "_id",
      foreignField: "productId",
      as: "productRates"
    }
  }
])

Conclusion

In this post, we have created a local docker environment with MongoDB containers and executed different aggregation queries in the MongoDB shell.

Let's do business

The project was co-financed by the European Union from the European Regional Development Fund. The content of the site is the sole responsibility of Serengeti ltd.
cross