I have a mongodb collection of following format :
{
"_id" : ObjectId("5141916511e5b498fd2031c4"),
"itemid" : 1,
"recommendations" : [
{
"itemid" : 216,
"rating" : 0.875297364790784
},
{
"itemid" : 246,
"rating" : 0.8793363655122852
}
]
}
{
"_id" : ObjectId("5141916511e5b498fd2031c5"),
"itemid" : 2,
"recommendations" : [
{
"itemid" : 60,
"rating" : 0.9405825249353504
},
{
"itemid" : 76,
"rating" : 0.8822827294664317
}
]
}
I want to retrieve recommendations for a given itemid and then iterate over it to print all the recommended itemids and ratings.I am using php for this.
When I try to iterate over returned cursor,it throws "Fatal error: Call to a member function hasNext() on a non-object" error. It seems the resultset returned by query is not of type cursor.
Below is the code I am using :
<?php
$mongodb = new Mongo("10.128.170.49:27017");
$database = $mongodb->ProductData;
$collection = $database->Recommendation1;
$cursor1 = $collection->findOne(array("itemid" => 1),array('recommendations'));
var_dump($cursor1);
echo "<hr/><p>iterating over a cursor</p>";
while ($cursor1->hasNext()): $document = $cursor1->getNext();
$itemid= $document['itemid'];
$probable_rating= $document['rating'];
echo ($itemid)."<br/>";
echo ($probable_rating)."<br/>";
echo "<hr/>";
endwhile;
?>
Please help me resolve this issue.
findOne()doesn't return a cursor. It returns a single object. You don't need to iterate for that.foreachinstead of awhileand then manually usinggetNext()foreachis not supported in V8, so newer versions of MongoDB no longer have that function.forEach