MongoDB

Join query in MongoDB

Hello. In this tutorial, we will understand how to perform join query in Mongodb. To set up Mongodb I will be using Docker.

1. Introduction

The $lookup operator in Mongodb is an aggregation operator and is used to perform join aggregate in Mongodb. This operator is used to join a document from one collection to a document in another collection of the same database. The operator works as a SQL Left Outer join and is represented by the following syntax in Mongodb –

Code syntax

{
    $lookup:
    {
        from: from_collection,
        localField: input_collection_field,
        foreignField: from_collection_field,
        as: attached_array_field
    }
}

Where:

  • from field indicates the mongodb collection with which we’d like to join
  • localField specifies the field local to a collection on which we need to perform the query
  • foreignField indicates the target field from other collections with which we intend to join
  • as specifies the name of the output array

2. Docker

In the present world, Docker is an important term –

  • Often used in CI/CD platform that packages and runs the application with its dependencies inside a container
  • Is a standard for Linux Containers
  • A Container is a runtime that runs under any Linux kernel and provides a private machine-like space under Linux

2.1 Setting up Docker

If someone needs to go through the Docker installation, please watch this video.

3. Join query in MongoDb

Let us start implementing this tutorial and understand the basis of the join operator in mongodb using the $lookup operator.

3.1 Setting up Mongodb on Docker

To set up the Mongodb and Mongodb GUI on the I will be making use of the Docker and for that, I have prepared a simple docker-compose.yml that will help to set up the mongodb with a default database as – test

docker-compose.yml

services:
  mongodb:
    container_name: mongodb
    image: mongo
    environment:
      MONGO_INITDB_DATABASE: test
    ports:
      - '27017:27017'
version: '3'

To get the mongodb up and running we will trigger the following command – docker-compose -f /docker-compose.yml up -d. If the images are not present in the host environment then they will be downloaded from the Dockerhub repository and the whole process might take a minute or two. Once done you can use the – docker ps command to confirm that the container is running or not as shown in the below image.

Fig. 1: Creating and running container

You can also use the following command – docker-compose -f /docker-compose.yml up -d to cleanup the created environment.

3.2 Setting up the implementation

Before starting with the tutorial I am hoping that you’re aware of the basis of the mongodb and docker.

3.2.1 Login to the mongodb container

We need to enter the running container with the help of the following command – docker exec -it mongodb bash as shown in the below figure. Here mongodb denotes the container name.

Fig. 2: Entering the mongodb docker container

3.2.2 Enter the mongodb shell

To enter the mongodb shell we need to use the following command – mongo as shown in the below figure. If the mongodb would have been initialized and started successfully during the container startup you will be able to enter the shell.

Fig. 3: Enter the mongodb shell

3.2.3 Populate the mongodb with collections

To understand the join query in mongodb using the $lookup operator we need to first create a database and add some collections to it. Let us start by creating a database and for that, we need to run the following command – use DATABASE_NAME in mongodb shell. For this tutorial, I will be playing around with test database.

Fig. 4: Creating a database

Once the db is created we need to create/add some dummy collections and I will be creating two collections named – batch and studentinfo. For creating the collection1 use the below command.

Collection1

db.batch.insertMany(
    [
        {
            "subject": "Science",
            "bid": 01,
            "name": "Bob",
            "is_active" : "yes",
			"days" : ["M","W","F"]
        },
        {
            "subject": "Maths",
            "bid": 02,
            "name": "Jack",
            "is_active" : "yes",
			"days" : ["M","W","F"]
        },
		{
            "subject": "Computers",
            "bid": 03,
            "name": "Adam",
            "is_active" : "yes",
			"days" : ["F"]
        },
    ]
);

Once done the following output will be shown on the console as in figure 5.

Fig. 5: Creating collection1

For creating collection2 use the below command.

Collection2

db.studentinfo.insertMany(
    [
        {
            "sname": "Bob",
            "standard": 12,
			"id": 101
        },
        {
            "sname": "Jack",
            "standard": 12,
			"id": 102
        },
		{
            "sname": "Adam",
            "standard": 10,
			"id": 103
        }
    ]
);

Once done the following output will be shown on the console as in figure 6.

Fig. 6: Creating collection2

You can even run the db.COLLECTION_NAME.find().pretty(); command to confirm whether the collections are created successfully or not.

Verifying the collections

db.batch.find().pretty();

db.studentinfo.find().pretty();

3.2.4 Running the join in mongodb

To understand the join in mongodb we will use the following command.

Collection2

db.studentinfo.aggregate([
    { $lookup:
        {
           from: "batch",
           localField: "sname",
           foreignField: "name",
           as: "batch_info"
        }
    }
]).pretty();

Once done the following output will be shown on the console as in figure 7. The image is cropped due to the content’s length.

Fig. 7: Running join operator in mongodb

That is all for this tutorial and I hope the article served you with whatever you were looking for. If you want to clean up the created collections use the drop() command. Happy Learning and do not forget to share!

4. Download the Project

This was a tutorial to understand and implement the $lookup operator in mongodb.

Download
You can download the full source code of this example here: Download

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button