得到对象而不是结果,我做错了吗?

时间:2017-07-26 18:08:39

标签: php mongodb

我有以下代码应该返回一组人员,但它会不断返回客户端对象。我按照文档。我已经使用mongo shell检查了数据是否存在。我不确定我做错了什么。

Mongodb:2.4.9

MongoClient:1.1

PHP:7.0

$collection = (new MongoDB\Client)->intranet->personnel;
$personnel = $collection->find([]);
var_dump($personnel);

这是我得到的结果

object(MongoDB\Driver\Cursor)#161 (9) {
  ["database"]=>
  string(8) "intranet"
  ["collection"]=>
  string(9) "personnel"
  ["query"]=>
  object(MongoDB\Driver\Query)#160 (3) {
    ["filter"]=>
    object(stdClass)#145 (0) {
    }
    ["options"]=>
    object(stdClass)#162 (0) {
    }enter code here
    ["readConcern"]=>
    NULL
  }
  ["command"]=>
  NULL
  ["readPreference"]=>
  object(MongoDB\Driver\ReadPreference)#143 (1) {
    ["mode"]=>
    string(7) "primary"
  }
  ["isDead"]=>
  bool(false)
  ["currentIndex"]=>
  int(0)
  ["currentDocument"]=>
  NULL
  ["server"]=>
  object(MongoDB\Driver\Server)#146 (10) {
    ["host"]=>
    string(9) "127.0.0.1"
    ["port"]=>
    int(27017)
    ["type"]=>
    int(1)
    ["is_primary"]=>
    bool(false)
    ["is_secondary"]=>
    bool(false)
    ["is_arbiter"]=>
    bool(false)
    ["is_hidden"]=>
    bool(false)
    ["is_passive"]=>
    bool(false)
    ["last_is_master"]=>
    array(5) {
      ["ismaster"]=>
      bool(true)
      ["maxBsonObjectSize"]=>
      int(16777216)
      ["maxMessageSizeBytes"]=>
      int(48000000)
      ["localTime"]=>
      object(MongoDB\BSON\UTCDateTime)#162 (1) {
        ["milliseconds"]=>
        string(13) "1501091758421"
      }
      ["ok"]=>
      float(1)
    }
    ["round_trip_time"]=>
    int(4)
  }
}

1 个答案:

答案 0 :(得分:0)

您的$personnel变量的内容是MongoCursor对象,而不是您期望成为结果数组的内容。为了根据您的查询检索值,您必须迭代MongoCursor上的每个项目。

e.g。

<?php

$collection = (new MongoDB\Client)->intranet->personnel;
$result = $collection->find();

$personnels = [];

foreach ($result as $personnel) {
    // do something to each document
    $personnels[] = $personnel;
}

var_dump($personnels);

或者您也可以使用PHP的iterator_to_array函数将其直接转换为数组。

<?php

$collection = (new MongoDB\Client)->intranet->personnel;
$personnels = iterator_to_array($collection->find());
var_dump($personnels);
相关问题