Joining MongoDB Collections Using PHP

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

  • All databases will eventually have performance-related issues as data stores grows. Taking simple steps to optimize the database will typically improve overall system performance. This tutorial will explain how to join MongoDB collections using PHP. In order to allow joining MongoDB collections using PHP, you must have MongoDB and the MongoDB PHP driver properly installed and configured on your machine.

Prerequisites

  • Confirm that you have the MongoDB and MongoDB PHP driver properly installed and configured.

  • Use the following command to see if you have the MongoDB driver installed:

1
pecl search mongo
  • The system should return something like this:
1
2
3
Package Stable/(Latest) Local
mongo 1.6.16 (stable) MongoDB database driver
mongodb 1.6.0alpha1 (alpha) 1.5.3 MongoDB driver for PHP
  • Use following command to determine what PHP version is installed on your system:
1
php --version
  • The system should return something like this:
1
2
3
4
PHP 7.2.15-0ubuntu0.18.04.2 (cli) (built: Mar 22 2019 17:05:14) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
with Zend OPcache v7.2.15-0ubuntu0.18.04.2, Copyright (c) 1999-2018, by Zend Technologies

How to Start the MongoDB Database Daemon

  • First, open your terminal by pressing the Ctrl + Alt + T keys.
  • Then start the MongoDB service and check the status using the command below.
  • You can use the sudo command to avoid permission-related issue while starting the MongoDB service.
1
2
sudo systemctl start mongod
sudo systemctl status mongod
  • The system should return something like this:
1
2
3
4
5
6
7
8
9
10
‚óè mongod.service - MongoDB Database Server
Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset:
Active: active (running) since Mon 2019-04-22 19:27:02 PST; 8min ago
Docs: https://docs.mongodb.org/manual
Main PID: 6598 (mongod)
CGroup: /system.slice/mongod.service
└─6598 /usr/bin/mongod --config /etc/mongod.conf

Apr 22 19:27:02 teamsolo systemd[1]: Started MongoDB Database Server.
lines 1-9/9 (END)

The Sample Data Set

  • The sample data sets for this article are as follows:

Subject Collection

IDPositionVisibleName
5ccd5c085431773e6f772cd51trueThe President
5ccc55305431777d196dbad41trueRommelDcode
  • Only two (2) items in the subject collection will be used for demo purposes in this tutorial.

Pages Collection

  • The following table displays four (4) items for the pages collection.
IDSubject IDContentPositionVisibleName
5cd2a1b45431770f6e6436935ccd5c085431773e6f772cd5This is just a sample content11Potus
5cd2a21454317709fe2ff4735ccd5c085431773e6f772cd5This is just a sample content21Potus History
5cd2b3d954317709fd4f09a35ccc55305431777d196dbad4This is just a sample content21Team Solo History
5cd2b8eb5431770f6e6436945ccd5c085431773e6f772cd5This is just a sample content30Potus Hobby

NOTE: There are some items that show the same Subject ID of 5ccd5c085431773e6f772cd5. This indicates these pages were related to the same document in the Subject Collection.

How to Join MongoDB Collections

  • This section will demonstrate how to join MongoDB collections.

Criteria for joining collections

  • Here is an example of how to join a collection and display documents that have the same subject_id and visible field value set to 1. To achieve this, use the following scripts:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
$con = new MongoDB\Client("mongodb://localhost:27017");
$collection = $con->abi_db->pages;

$ops = [ // (1)
'$lookup' =>[
'from' => 'subjects',
'localField' => $subId,
'foreignField' => '_id',
'as' => 'pageContent'
]
];

$SubjecID = [ // (2)
'$match'=>['subject_id'=>$subId, 'visible'=>1]
];
$showDetails = [ // (3)
'$project' => ['page_name' => 1, 'page_content' => 1, 'subject_id'=>1]
];

$result = $collection->aggregate( // (4)
[
$SubjecID,$showDetails,$ops
]
);

foreach ($result as $row){
echo "Page Name : " . $row['page_name']."
"
;
echo "Content : " . $row['page_content']."
"
;
echo "Subject ID: " . $row['subject_id']."
"
;
echo "
"
;


}
  1. $lookup — This command will perform a left outer join to an unsharded collection within the same database to filter documents. The $lookup stage adds a new array field composed of the elements from the matching documents from the joined collection.
  2. $match — This command will filter the document and allow only the documents that matches the defined criteria to pass through. This will output either one document, that matches the critera, or no document.
  3. $project — This will pass the documents with the specified fields to the next stage of the pipeline. This will perform the aggregated operation of joining the documents accordingly.
  • The returned results should resemble something like the this:
1
2
3
4
5
6
7
Page Name : Potus
Content : This is just a sample content.
Subject ID: 5ccd5c085431773e6f772cd5

Page Name : Potus History
Content : This is just a sample content.
Subject ID: 5ccd5c085431773e6f772cd5

Conclusion

This tutorial demonstrated how simple it is to go about joining MongoDB collections using PHP. The procedures outlined above are meant to be helpful for anyone who is just starting out using MongoDB as well as more experienced developers who are wanting to try out the MongoDB platform. Remember that you must have the MongoDB and MongoDB PHP driver properly installed and configured on your machine. When joining collections, bear in mind that some pages related to the same document will show the same alphanumeric Subject ID.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.