bob duncan
bob duncan

Reputation: 51

mongodb php findone() by ID

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

Upvotes: 4

Views: 20339

Answers (6)

Raj Nandan Sharma
Raj Nandan Sharma

Reputation: 3862

If you are using this the official driver then you should use this

$item = $db->findOne(array('_id' => new MongoDB\BSON\ObjectId($userid));

Upvotes: 3

nonshatter
nonshatter

Reputation: 3527

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/>";
    }

?>

Upvotes: 7

Alez
Alez

Reputation: 51

MongoDB needs integer variable to create the right query.

In my project it works like this :

<?php
$id = (int)$_GET["id"]; 
$cursor = $this->connect()->$db->$collection->find(array('_id' => $id));

Hope this helps someone!

Upvotes: 5

AbigailW
AbigailW

Reputation: 893

This post is a little stale, but in case anybody is researching this issue, here are a couple items to consider:

1) $item is an Array, so the code should probably read something more like this:

echo 'Item: ' . $item['name'] . '<br>';

2) also, the userid and itemid seem to be conflated in the original post. A more common pattern would be to set a 'uid' field in the items collection, so it has both an '_id' and 'uid' fields. Such as this:

$item = $db->find(array('uid' => $userid));

3) in this pattern, sometimes I find I need to cast the ObjectID or MongoID to a string, as follows:

$item = $db->findOne(array('uid' => (string)$userid));

4) but for a simple _id search, this is all you should need:

$item = $db->findOne(array('_id' => new MongoId($userid));

hope this helps!

Upvotes: 2

bm_i
bm_i

Reputation: 598

Does the result ($item) have the "_id" in it?

echo $item['_id'];

Upvotes: 0

Jagadeesan
Jagadeesan

Reputation: 1097

$item is an array. so print $item as below..

echo '<pre>';
print_r($item);
echo '</pre>';

Upvotes: 2

Related Questions