Skip to content
Advertisement

How to get mongodb collection iterator?

I’m connecting to mongo db like this:

$mongoClient = new MongoDBClient($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 ?

Advertisement

Answer

As stated in the documentation for the MongoDBClient class, the constructor does not perform the actual connection:

A MongoDBDriverManager is constructed internally. Per the Server Discovery and Monitoring specification, MongoDBDriverManager::__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.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement