PHP Mongo plugin: How to use $count parameter in Stage::search() method

Based on the official docs, the count option is a string, but when looking at the code, this is how the search method signature looks like:

public static function search(
    Document|Serializable|SearchOperatorInterface|stdClass|array $operator,
    Optional|string $index = Optional::Undefined,
    Optional|Document|Serializable|stdClass|array $highlight = Optional::Undefined,
    Optional|bool $concurrent = Optional::Undefined,
    Optional|Document|Serializable|stdClass|array $count = Optional::Undefined,
    Optional|string $searchAfter = Optional::Undefined,
    Optional|string $searchBefore = Optional::Undefined,
    Optional|bool $scoreDetails = Optional::Undefined,
    Optional|Document|Serializable|stdClass|array $sort = Optional::Undefined,
    Optional|bool $returnStoredSource = Optional::Undefined,
    Optional|Document|Serializable|stdClass|array $tracking = Optional::Undefined,
): SearchStage

As you can see, $count parameter must be any of Optional|Document|Serializable|stdClass|array types (no string), so I’m pretty confused regardind what I should pass in order to use the total option for counting results.

I tried something like this (using an array), but it’s throwing an error:

Stage::search(
    index: 'default',
    count: ['total'],
    returnStoredSource: true,
    // more options...
)

Thanks in advance for your help!

You should pass it like this:

Stage::search(
    index: 'default',
    count: ['type' => 'total'],
    returnStoredSource: true,
    // more options...
)

the docs may simplify it to a string, but the actual implementation expects an array with the configuration for the count parameter. The “total” value needs to be passed as the value for the “type” key in the array.

This is consistent with how atlas search works:
js

{
  $search: {
    // other search parameters
    count: { 
      type: "total"  // or "lowerBound"
    }
  }
}

iow in the PHP library, this translates to passing an array with the same structure.

1 Like

Thanks so much @daniel_scout! Yeah, I should have realized that :man_facepalming: .

1 Like

no worries! glad i could help!

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.