Lawrence Cooke
Lawrence Cooke

Reputation: 1597

Gettings Results from Mongo

I am adding documents to a MongoDB using PHP.

I have verified the documents have added successfully by using RockMongo.

However, When I run the find() command, it returns an empty array

$insert = $collection->insert($document);
$cursor = $collection->find();

The insert will insert the document, but find() returns "MongoCursor Object ( )"

Is there a command I need to run after the insert in order for the item to be available to find?

Upvotes: 0

Views: 86

Answers (1)

Gekkie
Gekkie

Reputation: 1056

as taken from the documentation: find returns a pointer to the resource and you must iterate over the results to actually see the results. (just like mysql(i)) http://php.net/manual/en/mongocollection.find.php

<?php

$m = new MongoClient();
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'produce');

// search for fruits
$fruitQuery = array('Type' => 'Fruit');

$cursor = $collection->find($fruitQuery);
foreach ($cursor as $doc) {
    var_dump($doc);
}

// search for produce that is sweet. Taste is a child of Details. 
$sweetQuery = array('Details.Taste' => 'Sweet');
echo "Sweet\n";
$cursor = $collection->find($sweetQuery);
foreach ($cursor as $doc) {
    var_dump($doc);
}

?>

So if you foreach over your results, it'll work fine!

Upvotes: 2

Related Questions