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
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/>";
}
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With