Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb php findone() by ID

Tags:

php

mongodb

This code will not find a record based on an ID search

<?php

$userid = $_GET['id'];

$theObjId = new MongoId($userid); 

$connection = new Mongo('localhost');

$db = $connection->test->items; 

$item = $db->findOne(array('_id' => $theObjId));

echo 'Item: ' . $item . '<br>';

echo 'UserID: ' . $userid . '<br>';

echo 'TheObjID: ' . $theObjId;

$connection->close(); 

?>

$userid is supplied by a form in another .php file

This is the output ....

$item: Array

 $userid: 4e0dfc8e7bfb8bac12000000

 $theObjId: 4e0dfc8e7bfb8bac12000000

the output proves my variables contain the ID

like image 937
bob duncan Avatar asked Dec 02 '22 02:12

bob duncan


1 Answers

I just had to do this, and didn't think the other answers answered the question.

Simply put, to query by Mongo ID (the _id field), use the MongoId object, then use the iterator_to_array function, which effectively copies the iterator into an array suitable for iteration:

<?php

    $doc_id = "4f917f15168cbe6364000032";

    $cursor = $collection->find(
        array(
            '_id' => new MongoId($doc_id)
        )
    );

    $cursor2array = iterator_to_array($cursor);
    echo "<pre>"; print_r($cursor2array); echo "</pre>";

    foreach ( $cursor2array[$doc_id] as $key => $value )
    {
         echo "$key => $value <br/>";
    }

?>
like image 157
nonshatter Avatar answered Dec 22 '22 05:12

nonshatter