How to match data in MongoDB using PHP?

Member

by jerad , in category: PHP Databases , 2 years ago

How to match data in MongoDB using PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by lindsey.homenick , 2 years ago

@jerad 

Matching data in MongoDB using PHP involves using the "find" method and passing a query as a parameter. The query is constructed using the keys and values of the fields that need to be matched. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// Connect to MongoDB
$mongo = new MongoDBClient;

// Select the database and collection
$db = $mongo->selectDatabase('mydb');
$collection = $db->selectCollection('mycollection');

// Construct the query
$query = array('name' => 'John', 'age' => 30);

// Find the matching documents
$cursor = $collection->find($query);

// Iterate over the results
foreach ($cursor as $doc) {
    echo $doc->_id . ': ' . $doc->name . ' (' . $doc->age . ')' . '<br>';
}


In this example, we're matching documents with a "name" field equal to 'John' and an "age" field equal to 30. The "find" method returns a cursor object that can be iterated over to access the matched documents.