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

Integrate pipeline builder with aggregate() and watch() methods

    • Type: Icon: New Feature New Feature
    • Resolution: Fixed
    • Priority: Icon: Unknown Unknown
    • 1.21.0
    • Affects Version/s: None
    • Component/s: None
    • None
    • PHP Drivers
    • Needed
    • Hide

      Document creation of aggregation pipeline using the new Builder API.
      Using this pipeline with the Collection::aggregate() method.

      Show
      Document creation of aggregation pipeline using the new Builder API. Using this pipeline with the Collection::aggregate() method.

      • Accept a MongoDB\Builder\Pipeline as argument for DB::aggregate, Collection::aggregate, Client::watch, DB::watch, and Collection::watch methods
      • Pipeline is encoded to BSON using the encoder provided in the client/database/collection options

      Since we cannot change the type of the $pipeline argument in the mentioned methods, we can only accept a list of Stage objects. In the version 1.20+, the code look like this:

      $pipeline = new Pipeline(
          Stage::match(...),
          Stage::limit(...),
      );
      
      // Required for now, as we could not change the argument type. In 2.0 this will not be necessary.
      $pipeline = iterator_to_array($pipeline);
      
      $pipeline = (new CustomBuilderEncoder)->encode($pipeline);
      $collection->aggregate($pipeline);
      

      It's possible to enable the new behavior in a class extending MongoDB\Collection:

      use MongoDB\Builder\Pipeline;
      use MongoDB\Collection;
      
      class CustomCollection extends Collection
      {
          /** @param array|Pipeline $pipeline */
          public function aggregate(array|Pipeline $pipeline = [], array $options = [])
          {
              // Enable behavior of version 2.0: Pipeline objects are accepted
              if ($pipeline instanceof Pipeline) {
                  $pipeline = iterator_to_array($pipeline);
              }
      
              return parent::aggregate($pipeline, $options);
          }
      
          /** @param array|Pipeline $pipeline */
          public function watch(array|Pipeline $pipeline = [], array $options = [])
          {
              // Enable behavior of version 2.0: Pipeline objects are accepted
              if ($pipeline instanceof Pipeline) {
                  $pipeline = iterator_to_array($pipeline);
              }
      
              return parent::watch($pipeline, $options);
          }
      }
      

            Assignee:
            jerome.tamarelle@mongodb.com Jérôme Tamarelle
            Reporter:
            jmikola@mongodb.com Jeremy Mikola
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: