0

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!!

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1
$cursor = $collection->find(array('game' => 'Borderlands 2'));
while ($document = $cursor->getNext()){
      echo $document['game'];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.