如何获取mongodbcollection迭代器?
How to get mongodb collection iterator?
我正在像这样连接到 mongo 数据库:
$mongoClient = new MongoDB\Client($db_string);
像这样获得collection:
$collection = $mongoClient->selectCollection('database_name', 'collection_name');
并像这样获得 collection 迭代器:
$iterator = $collection->find();
但是最后一次调用会报错:
[错误] 无法从 demo_article 检索源计数:身份验证失败。
我哪里做错了?
更新:
这里:
protected function initializeIterator()
{
$this->iterator = $this->collection->find();
if($this->iterator instanceof Traversable) {
echo "**Traversable!**";
}
迭代器是可遍历的。但是,这段代码是从 SourcePluginBase 调用的:
protected function doCount() {
$iterator = $this->getIterator();
if($iterator instanceof Traversable) {
echo "**TRAVERSABLE!**";
}else{
echo "**NOT TRAVERSABLE!**";
}
它不是可遍历的?!它怎么会失去那种可穿越的地位?
如 MongoDB\Client
class 的文档中所述,构造函数不执行实际连接:
A MongoDB\Driver\Manager is constructed internally. Per the Server Discovery and Monitoring specification, MongoDB\Driver\Manager::__construct() performs no I/O. Connections will be initialized on demand, when the first operation is executed.
表示只有在执行第一个查询时才会打开连接。如果您在连接字符串中没有提供凭据,或者它们不正确,那么您会在该查询中收到“身份验证失败”错误。
我正在像这样连接到 mongo 数据库:
$mongoClient = new MongoDB\Client($db_string);
像这样获得collection:
$collection = $mongoClient->selectCollection('database_name', 'collection_name');
并像这样获得 collection 迭代器:
$iterator = $collection->find();
但是最后一次调用会报错:
[错误] 无法从 demo_article 检索源计数:身份验证失败。
我哪里做错了?
更新:
这里:
protected function initializeIterator()
{
$this->iterator = $this->collection->find();
if($this->iterator instanceof Traversable) {
echo "**Traversable!**";
}
迭代器是可遍历的。但是,这段代码是从 SourcePluginBase 调用的:
protected function doCount() {
$iterator = $this->getIterator();
if($iterator instanceof Traversable) {
echo "**TRAVERSABLE!**";
}else{
echo "**NOT TRAVERSABLE!**";
}
它不是可遍历的?!它怎么会失去那种可穿越的地位?
如 MongoDB\Client
class 的文档中所述,构造函数不执行实际连接:
A MongoDB\Driver\Manager is constructed internally. Per the Server Discovery and Monitoring specification, MongoDB\Driver\Manager::__construct() performs no I/O. Connections will be initialized on demand, when the first operation is executed.
表示只有在执行第一个查询时才会打开连接。如果您在连接字符串中没有提供凭据,或者它们不正确,那么您会在该查询中收到“身份验证失败”错误。