How to Create Different Types of Index in MongoDB using PHP

Introduction

This tutorial teaches about creating different types of index in MongoDB using PHP. The benefit of being able to accomplish this task is that you gain flexibility in how you construct indexes. The more personalized indexes are to your needs, the better they will serve you. Find out how. Let’s begin our lesson.

Prerequisites

*The command pecl ensures that you installed the MongoDB driver:

pecl search mongo
  • Here’s what a successful result looks like:
Package Stable/(Latest) Local
mongo 1.6.16 (stable) MongoDB database driver
mongodb 1.6.0alpha1 (alpha) 1.5.3 MongoDB driver for PHP
  • Next, find out the version of your PHP driver. Use this command:
php --version
  • Here’s what a successful result. Yours should resemble something close to this:
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
  • This is a nice PHP Driver and MongoDB version compatibility chart for you to reference.

table mongodb php driver

The Fast Way to Start the MongoDB Service

  • Use Ctrl + Alt + T to open your terminal. A new window should appear.

  • The sudo commands allow you to access the system and avoid errors when doing so. Use both commands listed below to start the service for MongoDB and do a status check as well.

sudo systemctl start mongod
sudo systemctl status mongod
  • Notice the “active running” result next to “Active.” When MongoDB is running, the result should resemble this:

starting mongod service

How to Use PHP to Create an Index in MongoDB

  • The script below uses the MongoDB\Driver\Manager and the PHP Library to create a MongoDB index.
// Using MongoDB\Driver\Manager

$db = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$query = new \MongoDB\Driver\Query(['createIndex' => ['topic_name' => 1]]);
$db->executeQuery('abi_db.subjects', $query);


// Using PHP Library


$con = new MongoDB\Client("mongodb://localhost:27017");
$db = $con->abi_db;
$collection = $db->subjects;
$indexName = $collection->createIndex(['topic_name' => 1]);
  • Save it and name the script “createIndex.php”.

  • Open your web browser and navigate to it.

  • Next, look at the page’s “View Page Source”.

  • Here’s an example of what a successful result should look like:


GeSHi Error: GeSHi could not find the language json (using path /nas/content/live/orkbprod/wp-content/plugins/codecolorer/lib/geshi/) (code 2)

Use PHP to Create a Unique Index in MongoDB

  • To the “createIndex.php” page you just saved, add unique => 1 to make the index unique.
// Using MongoDB\Driver\Manager

$db = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$query = new \MongoDB\Driver\Query(['createIndex' => ['topic_name' => 1], ['unique' => 1]]);
$db->executeQuery('abi_db.subjects', $query);


// Using PHP Library


$con = new MongoDB\Client("mongodb://localhost:27017");
$db = $con->abi_db;
$collection = $db->subjects;
$indexName = $collection->createIndex(['topic_name' => 1],['unique' => 1]);
  • To keep the changes you just made, save the page again, then refresh it.

  • Now, verify the page’s “View Page Source”.

  • Your newly edited “createIndex.php” page should look similar to this:


GeSHi Error: GeSHi could not find the language json (using path /nas/content/live/orkbprod/wp-content/plugins/codecolorer/lib/geshi/) (code 2)

>NOTE: With the script below, you can easily determine if your PHP script was successful. It uses the db.collection.getIndexes() shell command in MongoDB. Here it is:

> db.subjects.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "abi_db.subjects"
},
{
"v" : 2,
"unique" : true,
"key" : {
"topic_name" : 1
},
"name" : "topic_name_1",
"ns" : "abi_db.subjects"
}
]
  • The unique index modification worked!

Conclusion

This tutorial went over creating different types of index in MongoDB using PHPx000D. We showed you how to create a standard MongoDB index. We also went over how to create a unique => 1 index to further customize your index. It’s also important to test the success of your scripts to verify that they’ll work for you in the way you require. The processes we discussed showed appropriate examples of that as well. Go ahead and try these methods for your projects now and enjoy the flexibility of indexes you create in MongoDB.

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.