{"record":{"id":"a87630ee23180749","repo":"mongodb/laravel-mongodb","slug":"the-relation-key-of-type-s-cannot-be-used-to-match","errorCode":null,"errorMessage":"The relation key of type \"%s\" cannot be used to match aggregated values.","messagePattern":"The relation key of type \"(.+?)\" cannot be used to match aggregated values\\.","errorType":"exception","errorClass":"InvalidArgumentException","httpStatus":null,"severity":"error","filePath":"src/Helpers/QueriesRelationshipAggregates.php","lineNumber":283,"sourceCode":"            'sum' => $values->sum($column),\n            'avg' => $values->avg($column),\n            'min' => $values->min($column),\n            'max' => $values->max($column),\n        };\n    }\n\n    /** Document keys are compared as strings, as ObjectId instances are not identical. */\n    private static function aggregateKey(mixed $value): string\n    {\n        if ($value instanceof Binary) {\n            return bin2hex($value->getData());\n        }\n\n        if (is_scalar($value) || $value instanceof Stringable) {\n            return (string) $value;\n        }\n\n        throw new InvalidArgumentException(sprintf(\n            'The relation key of type \"%s\" cannot be used to match aggregated values.',\n            get_debug_type($value),\n        ));\n    }\n\n    private function assertAggregateRelationSupported(Relation $relation, string $name): void\n    {\n        if ($relation instanceof EmbedsOneOrMany) {\n            return;\n        }\n\n        if (! DocumentModel::isDocumentModel($relation->getRelated()) || $this->isAcrossConnections($relation)) {\n            throw new LogicException(sprintf(\n                'Aggregating the hybrid relation \"%s\" is not supported. The related model must be stored in MongoDB.',\n                $name,\n            ));\n        }\n","sourceCodeStart":265,"sourceCodeEnd":301,"githubUrl":"https://github.com/mongodb/laravel-mongodb/blob/0634653039468ceb0268a69192bdac64469ed043/src/Helpers/QueriesRelationshipAggregates.php#L265-L301","documentation":"When hydrating grouped aggregates (HasOneOrMany withAggregate), the library matches aggregate results to parent models by stringifying the relation key (parent local key / foreign key). If that key value is neither scalar, Stringable, nor a BSON Binary (e.g. an array, DateTime, or ObjectId handled elsewhere), it cannot be converted to a comparable string key, so an InvalidArgumentException is thrown.","triggerScenarios":"Using withCount/withSum etc. on a HasOneOrMany relation where the parent key attribute (e.g. _id or custom local key) contains a non-scalar value such as an embedded array or date object that is not Stringable, e.g. Model::withCount('items') where items' local key is an array field.","commonSituations":"Custom key setups: using a date, embedded document, or array as the relation key instead of an _id/scalar; documents written by other systems with unexpected key types; MongoDate/typed values not cast to string by the model's casts.","solutions":["Ensure the relation key attribute (local key / foreign key) is a scalar or Stringable value, typically an ObjectId or integer.","Add a model cast (e.g. 'datetime' or a custom cast implementing Stringable) so the key attribute resolves to a string.","Inspect the offending document and fix the stored key type in the collection."],"exampleFix":"// before\nclass Order extends DocumentModel {\n    protected $casts = ['group_ref' => 'array']; // used as local key\n}\n// after\nclass Order extends DocumentModel {\n    protected $casts = ['group_ref' => 'string']; // scalar key usable for aggregate matching\n}","handlingStrategy":"type-guard","validationCode":"// Verify the parent key attribute is scalar/Stringable before aggregating\n$key = $model->getAttribute($parentKey);\nif (!is_scalar($key) && !$key instanceof Stringable && !$key instanceof \\MongoDB\\BSON\\Binary) {\n    throw new InvalidArgumentException('Relation key must be scalar or Stringable.');\n}","typeGuard":"function isUsableAggregateKey(mixed $v): bool {\n    return is_scalar($v) || $v instanceof Stringable || $v instanceof \\MongoDB\\BSON\\Binary;\n}","tryCatchPattern":"try {\n    $users = User::withCount('orders')->get();\n} catch (\\InvalidArgumentException $e) {\n    // inspect/repair documents whose relation key has an unsupported type\n    logger()->error($e->getMessage());\n    throw $e;\n}","preventionTips":["Use ObjectId, integer, or string values as relation keys.","Declare casts for key attributes so they resolve to scalar/Stringable types.","Audit collections for documents with array or date values in key fields."],"tags":["mongodb","eloquent","aggregate","type-mismatch","invalid-argument"],"backgroundTag":"type-mismatch","analyzedSha":"0634653039468ceb0268a69192bdac64469ed043","analyzedAt":"2026-09-15T02:56:37.067Z","contentChangedAt":"2026-09-15T02:56:37.067Z","schemaVersion":2},"datasetVersion":"2026-09-16T09:17:16.951Z"}