获取对象而不是结果,我做错了什么吗?



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

蒙戈德:2.4.9

蒙戈客户端:1.1

菲律宾比索: 7.0

$collection = (new MongoDBClient)->intranet->personnel;
$personnel = $collection->find([]);
var_dump($personnel);

这是我得到的结果

object(MongoDBDriverCursor)#161 (9) {
["database"]=>
string(8) "intranet"
["collection"]=>
string(9) "personnel"
["query"]=>
object(MongoDBDriverQuery)#160 (3) {
["filter"]=>
object(stdClass)#145 (0) {
}
["options"]=>
object(stdClass)#162 (0) {
}enter code here
["readConcern"]=>
NULL
}
["command"]=>
NULL
["readPreference"]=>
object(MongoDBDriverReadPreference)#143 (1) {
["mode"]=>
string(7) "primary"
}
["isDead"]=>
bool(false)
["currentIndex"]=>
int(0)
["currentDocument"]=>
NULL
["server"]=>
object(MongoDBDriverServer)#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(MongoDBBSONUTCDateTime)#162 (1) {
["milliseconds"]=>
string(13) "1501091758421"
}
["ok"]=>
float(1)
}
["round_trip_time"]=>
int(4)
}
}

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

例如

<?php
$collection = (new MongoDBClient)->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 MongoDBClient)->intranet->personnel;
$personnels = iterator_to_array($collection->find());
var_dump($personnels);

相关内容

最新更新