Home > Mobile >  How to get mongodb collection iterator?
How to get mongodb collection iterator?

Time:11-02

I'm connecting to mongo db like this:

$mongoClient = new MongoDB\Client($db_string);

Getting collection like this:

$collection = $mongoClient->selectCollection('database_name', 'collection_name');

And getting collection iterator like this:

$iterator = $collection->find();

However last call shoots error:

[error] Could not retrieve source count from demo_article: Authentication failed.

What I'm doing wrong here?

UPDATE:

Here:

  protected function initializeIterator()
  {
    $this->iterator = $this->collection->find();
    if($this->iterator instanceof Traversable) {
      echo "**Traversable!**";
    }

iterator is Traversable. But then, this code is called from SourcePluginBase:

  protected function doCount() {
    $iterator = $this->getIterator();
    if($iterator instanceof Traversable) {
      echo "**TRAVERSABLE!**";
    }else{
      echo "**NOT TRAVERSABLE!**";
    }

and it's not Traversable?! How can it loos that traversable status ?

CodePudding user response:

As stated in the documentation for the MongoDB\Client class, the constructor does not perform the actual connection:

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.

It means that the connection will be opened only when you execute the first query. If you provided no credentials in the connection string, or if they are incorrect, then you get an "Authentication failed" error on that query.

  • Related