PHP操作MongoDB,怎么把一个集合转为数组?

使用MongoDB PHP Library来操作mongodb数据库,
https://docs.mongodb.com/php-...
从MongoDB查询出来的是一个集合,我想把它转为数组,应该怎么做呢?

比如下面这个示例,我想把$cursor转为数组:

    $collection = (new MongoDB\Client)->test->zips;
    
    $cursor = $collection->find(['city' => 'JERSEY CITY', 'state' => 'NJ']);
    
    foreach ($cursor as $document) {
        echo $document['_id'], "\n";
    } 
阅读 6.7k
3 个回答
<?php
    $manager     = new MongoDB\Driver\Manager("mongodb://localhost:27017"); 
    $bulk         = new MongoDB\Driver\BulkWrite;
    $bulk->insert(['x' => 1, 'name'=>'菜鸟教程',     'url' => 'http://www.runoob.com']);
    $bulk->insert(['x' => 2, 'name'=>'Google',     'url' => 'http://www.google.com']);
    $bulk->insert(['x' => 3, 'name'=>'taobao',     'url' => 'http://www.taobao.com']);
    $manager->executeBulkWrite('test.sites', $bulk);
    $filter     = ['x' => ['$gt' => 1]];
    $options     = [
            'projection'     => ['_id' => 0],
            'sort'         => ['x' => -1],
    ];
    $query         = new MongoDB\Driver\Query($filter, $options);
    $cursor     = $manager->executeQuery('test.sites', $query);
    $arr        = $cursor->toArray();
    print_r($arr);

图片描述

一个很容易理解的方法,声明空数组例如$arr=[],foreach循环内部$arr[]=$document['_id];

find方法返回Cursor。

  1. 可以直接使用Cursor的toArray方法。

    $cursor = $collection->find(['city' => 'JERSEY CITY', 'state' => 'NJ']);
    $cursor->toArray()
  2. 可以使用PHP的方法iterate_to_array

    $cursor = $collection->find();
    var_dump(iterator_to_array($cursor));

我对PHP了解不多,以上是搜索文档找出来的内容,自己验证一下~

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题