【问题标题】:How to print_r in PHP a MongoDB Collection?如何在 PHP 中打印一个 MongoDB 集合?
【发布时间】:2011-07-18 21:58:46
【问题描述】:

find()ing 我的结果后,如何使用 MongoDB 集合查看和“执行”操作?即:

<?php
   $cursor = $collection->find();
   json_encode($cursor);
   //OR
   print_r($cursor);
?>

等等。无论我做什么,我什么都得不到,但是如果我循环它,我可以一个一个地取出数据,我可以取出数据(当然)但问题是,我想用它做一些事情,比如对返回的数组进行编码作为一个整体到一个 JSON 对象来做 AJAX / JS 的东西。

那么,我该怎么做呢?

【问题讨论】:

    标签: javascript php ajax mongodb database


    【解决方案1】:

    您正在尝试在 MongoCursor 上执行 print_r,而不是 PHP 数组(这不起作用。)

    http://php.net/manual/en/class.mongocursor.php

    您需要将光标转换为 PHP 数组 ...

    <?
    // Connect to Mongo and set DB and Collection
    $mongo = new Mongo();
    $db = $mongo->twitter;
    $collection = $db->tweets;
    
    // Return a cursor of tweets from MongoDB
    $cursor = $collection->find();
    
    // Convert cursor to an array
    $array = iterator_to_array($cursor);
    
    // Loop and print out tweets ...
    foreach ($array as $value) {
       echo "<p>" . $value[text];
       echo " @ <b><i>" . $value[created_at] . "</i></b>";
    }
    ?>
    

    或者,使用 findOne() 代替它不会返回 MongoCursor ...因此,如果您只想获取一个文档并将其作为 JSON 返回到您的应用程序,您可以像这样简单地进行操作(这说明了如何做你问的 JSON 和 print_r)...

    查看这些文章以获得更多帮助...

    http://learnmongo.com/posts/mongodb-php-install-and-connect/

    http://learnmongo.com/posts/mongodb-php-twitter-part-1/

    <?php
    
    $connection = new Mongo();
    $db = $connection->test;
    $collection = $db->phptest;
    
    $obj = $collection->findOne();
    echo "<h1>Hello " . $obj["hello"] . "!</h1>";
    
    echo "<h2>Show result as an array:</h2>";
    echo "<pre>";
    print_r($obj);
    echo "</pre>";
    
    echo "<h2>Show result as JSON:</h2>";
    echo "<pre>";
    echo json_encode($obj);
    echo "</pre>";
    
    ?>
    

    【讨论】:

      【解决方案2】:

      标准是使用 foreach 或 while 循环遍历结果。

      还有(作为 PHP 版本 > 5.1 的一部分)iterator_to_array,可以与 Mongo 游标一起使用。正如Mongo::find 上的注释,这会将所有结果加载到内存中, 这可能会超出内存限制并导致脚本崩溃 - 因此请注意预期的数据量。

      $cursor = $collection->find();
      $array = iterator_to_array($cursor);.
      

      【讨论】:

      【解决方案3】:

      使用 shell,您可以查询 Mongo,它将结果作为数组输出。

      db.products.find().toArray()
      

      上面将打印格式为数组的集合“产品”。我还没有测试过,但你可以使用 PHP 获取输出并进行打印。只是一个想法。

      【讨论】:

        猜你喜欢
        • 2022-01-20
        • 2020-07-21
        • 1970-01-01
        • 2012-12-03
        • 1970-01-01
        • 2021-01-01
        • 2017-04-16
        • 2020-09-12
        • 1970-01-01
        相关资源
        最近更新 更多