Reputation: 1838
So I'm learning MongoDB and everything was working fine until I wanted to query and discovered that it returns an array that does not work the way I'm used to. Take the example:
$cursor = $collection->find(array('game' => 'Borderlands 2'));
$array = iterator_to_array($cursor);
So far so good, but then I wanted to get a single value to add dynamically to a page:
The game is: <?php echo $array['game'] ?>
And only errors followed. I tried tons of things but then I var_dump
it and found that the array is contained under a ID/index array, so this worked:
<?php echo $array["5138225097777c4014000001"]["game"] ?>
I couldn't find any explanation around. Though I understand now how it works, I'm not sure if this is a mistake I made when adding the values to the collection or if I'm missing something. Thanks!!
Upvotes: 0
Views: 72
Reputation: 16307
$cursor = $collection->find(array('game' => 'Borderlands 2'));
while ($document = $cursor->getNext()){
echo $document['game'];
}
Upvotes: 1
Reputation: 6520
This is because find returns an array of results(and each result is converted to an array). Hence you have an array of results with the Mongo ObjectId as the key in the array. Use findOne if you want to get just one result.
Upvotes: 2