How to create an index in MongoDB using PHP?

Member

by aubrey , in category: PHP Databases , a year ago

How to create an index in MongoDB using PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lottie , a year ago

@aubrey 

To create an index in MongoDB using PHP, you can use the MongoCollection::createIndex() method. This method takes two arguments: the first argument is an array of field names that you want to index, and the second argument is an array of options for the index.


Here's an example code snippet that creates an index on a MongoDB collection using PHP:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<?php

// Connect to MongoDB
$mongo = new MongoClient();

// Select a database and collection
$db = $mongo->mydb;
$collection = $db->mycollection;

// Define the index
$index = array("field1" => 1, "field2" => -1);

// Set the index options
$options = array("name" => "my_index", "unique" => true);

// Create the index
$collection->createIndex($index, $options);

?>


In this example, the createIndex() method creates an index on two fields (field1 and field2) with ascending and descending order respectively. The options parameter is used to specify the name of the index as well as set it as a unique index.