Uploaded image for project: 'PHP Driver: Library'
  1. PHP Driver: Library
  2. PHPLIB-327

ChangeStream::next() should not increment key for the first event

    • Type: Icon: Bug Bug
    • Resolution: Fixed
    • Priority: Icon: Minor - P4 Minor - P4
    • 1.3.1
    • Affects Version/s: 1.3.0
    • Component/s: None
    • None

      Given the following script to iterate a change stream:

      $collection = (new MongoDB\Client($uri))->test->inventory;
      $collection->drop();
      
      $changeStream = $collection->watch();
      
      for ($changeStream->rewind(); true; $changeStream->next()) {
          if ( ! $changeStream->valid()) {
              continue;
          }
      
          $event = $changeStream->current();
      
          printf("%d: %s\n", $changeStream->key(), $event['operationType']);
      }
      

      And a second script to populate it with some events:

      $collection = (new MongoDB\Client($uri))->test->inventory;
      
      $result = $collection->insertOne(['name' => 'Widget', 'quantity' => 5]);
      $collection->updateOne(['_id' => $result->getInsertedId()], ['$inc' => ['quantity' => -1]]);
      $collection->deleteOne(['_id' => $result->getInsertedId()]);
      

      I would expect the following output from the first script:

      0: insert
      1: update
      2: delete
      

      However, the key of the first "insert" starts at 1. This is likely due to ChangeStream::next() always incrementing the key counter. We might need to make a special allowance to only increment when we're advancing from a previous element.

      Note: if the second script were executed between the call to Collection::watch() and ChangeStream::rewind(), the first key would be 0 as expected.

            Assignee:
            katherine.walker@mongodb.com Katherine Walker (Inactive)
            Reporter:
            jmikola@mongodb.com Jeremy Mikola
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: