mongodb php findone()通过ID [英] mongodb php findone() by ID

查看:318
本文介绍了mongodb php findone()通过ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码将不会基于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由另一个.php文件中的表单提供

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

这是输出....

$item: Array

 $userid: 4e0dfc8e7bfb8bac12000000

 $theObjId: 4e0dfc8e7bfb8bac12000000

输出证明我的变量包含ID

the output proves my variables contain the ID

推荐答案

我只需要这样做,就没有其他答案回答了这个问题.

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

简单地说,要通过Mongo ID(_id字段)进行查询,请使用 MongoId 对象,然后使用 iterator_to_array 函数,有效地将迭代器复制到适合迭代的数组中:

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

?>

这篇关于mongodb php findone()通过ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆