Uploaded image for project: 'C++ Driver'
  1. C++ Driver
  2. CXX-2659

Add `change_stream::next()`

    • Type: Icon: Improvement Improvement
    • Resolution: Unresolved
    • Priority: Icon: Unknown Unknown
    • None
    • Affects Version/s: None
    • Component/s: API
    • None

      Proposed changes

      • Add a change_stream::next() method to iterate a changes stream until an event or error occurs.

      Background & Motivation

      Change stream iteration has been a source of several questions: CXX-2435, CXX-2278, and HELP-28966.

      Having multiple iterators to the same change stream seems to have no use case. change_stream::begin() documents this:

      The state of all iterators is tracked by the change_stream itself, so advancing one iterator advances all iterators.

      IMO the iterator returned by change_stream::begin() does not add much value to the API. A common use case is to wait until the next notification or error. With the current API, iteration must be restarted each time:

      while (true) {
          for (const auto& event : stream) {
              std::cout << bsoncxx::to_json(event) << std::endl;
          }
          // Iteration stops once the server responds with an empty batch.
          // There may still be more events.
          // Iterate again to send another `getMore`.
      }
      

      With the new API, this is done with one loop:

      while (true) {
          const auto& event = stream.next(); // Only returns when a new document is available.
          std::cout << bsoncxx::to_json(event) << std::endl;
      }
      

      The method name next matches some other driver iteration methods (Java, Go, PHP). See https://www.mongodb.com/docs/manual/changeStreams/

      A caveat of this proposal: Using an iterator is consistent with the mongocxx::cursor API. Using an iterator enables Range-based for loops.

            Assignee:
            Unassigned Unassigned
            Reporter:
            kevin.albertson@mongodb.com Kevin Albertson
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated: