@Shibbir That error occurs when there is no matching_competitors key in a document. That means, it is not an empty array, but is completely missing.
Something like this can be done. I don't know if it is the best way or not.
$found_ids = collect(
DB::connection('mongodb')
->collection('products_' . $id_project)
->raw(function ($collection) {
return $collection->aggregate([
[
'$project' => [
'count' => [
'$size' => [
'$ifNull' => ['$matching_competitors', []], // If null, set as []
],
],
],
],
[
'$match' => [
'count' => [
'$eq' => 3, // <- your number
],
],
],
]);
})
->toArray()
)->map(fn($d) => (string) $d['_id']);
$records = DB::connection('mongodb')
->collection('products_' . $id_project)
->whereIn('_id', $found_ids)
->get();
With this way, 2 queries are needed. And, you need to manually handle paginations with skip/limit etc.