[CXX-2659] Add `change_stream::next()` Created: 06/Mar/23  Updated: 07/Feb/24

Status: Backlog
Project: C++ Driver
Component/s: API
Affects Version/s: None
Fix Version/s: None

Type: Improvement Priority: Unknown
Reporter: Kevin Albertson Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Epic Link: C++ Developer Experience Improvements

 Description   

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.


Generated at Wed Feb 07 22:06:37 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.