Reputation: 549
I am trying to implement text search in MongoDB using PHP. I have created necessary text index on the collection and Mongo queries with operators $text , $search are working fine. However, using PHP, I am facing a few errors to search documents in mongodb collection.
Here is my code:
<html>
<body>
<h3>MongoDB Test</h3>
<h2>Text search - Amazon reviews</h2>
<br>
<form method="post">
search: <input type="text" name="term"><br><br>
<input type="submit">
</form>
</body>
</html>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$term = $_REQUEST['term'];
// connect to mongodb : default is localhost:27017
$m = new MongoClient();
echo "Connection to database successfully"."</br>";
// select a database
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'reviews');
$query = array('$text' => array('$search'=> $term));
$cursor = $collection->find($query);
var_dump($cursor);
echo '<table border="1"><tr><td>Review Title</td><td>Author</td><td>Rating</td></tr>';
foreach ($cursor as $doc) {
echo '<tr>';
echo '<td>'.$doc['Reviews.Title'].'</td>'.
'<td>'.$doc['Reviews.Author'].'</td>'.
'<td>'.$doc['Reviews.Overall'].'</td>';
echo '</tr>';
}
echo '</table>';
}
?>
Error: Connection to database successfully object(MongoCursor)#4 (0) { } Notice: Undefined index: Reviews.Title in C:\xampp\htdocs\MongoSearch\index.php on line 41
Notice: Undefined index: Reviews.Author in C:\xampp\htdocs\MongoSearch\index.php on line 42
Notice: Undefined index: Reviews.Overall in C:\xampp\htdocs\MongoSearch\index.php on line 43
Notice: Undefined index: Reviews.Title in C:\xampp\htdocs\MongoSearch\index.php on line 41
Notice: Undefined index: Reviews.Author in C:\xampp\htdocs\MongoSearch\index.php on line 42
Notice: Undefined index: Reviews.Overall in C:\xampp\htdocs\MongoSearch\index.php on line 43
Can anyone point out the mistake in this code? Text index is properly built on this collection. Below mongo query is working fine on the collection.
db.getCollection('reviews').find({$text: {$search : 'terrible'}})
This is structure of the resulting document:
{
"_id" : ObjectId("571a3c99fef93833794475d4"),
"Reviews" : {
"Title" : "Terrible, Terrible, Terrible!",
"Author" : "authoradasdjlasd",
"Overall" : "1.0",
"Content" : "battery will die.I hope this helps!!",
"Date" : "September 9, 2013"
},
"ProductInfo" : {
"Name" : "Kyocera Rise (Virgin Mobile)",
"ProductID" : "B008P2UVT0"
}
}
The main problem here is that I am getting 0 documents as a result. I doubt on mongo query translation to PHP code. i.e.
$query = array('$text' => array('$search'=> $term));
$cursor = $collection->find($query);
Upvotes: 2
Views: 2750
Reputation: 2966
It literally means that your $doc
does not have Reviews.Title
key. I don't know what's your structure but it looks like you are unnecessary adding Reviews.
to the key or if it's embedded document you should be accessing it with $doc['Reviews']['Title']
. Either way, try var_dump
ing your $doc
to see what is in it.
Upvotes: 2