I have encountered an issue with an aggregation query in my PHP application. The purpose of this query is to retrieve data from a MongoDB collection while applying different limits based on domain IDs. However, the query is not delivering the expected results in terms of separate limits for each domain ID.
$domainLimits = array(
1 => 5, // email_domain_id 1 limit
2 => 4, // email_domain_id 2 limit
);
$opn = array(
array('$match' => $match_array2),
array('$project' => array(
'contact_email_id' => '$contact_email_id',
'publisher_id' => '$publisher_id',
'contact_id' => '$contact_id',
'email_domain_id' => '$email_domain_id',
'cmp_value' => array(
'$cmp' => array(
'$usage_limit',
'$usedlimit.' . date('l', $unsusbcribe[0]->schedule_date)
)
),
)),
array('$match' => array(
'cmp_value' => array('$gt' => 0)
)),
array('$group' => array(
'_id' => '$contact_email_id',
'object_id' => (array('$last' => '$_id')),
'publisher_id' => array('$last' => '$publisher_id'),
'contact_id' => array('$last' => '$contact_id'),
'email_domain_id' => array('$last' => '$email_domain_id')
)),
array('$sort' => array('_id' => -1)),
array('$group' => array(
'_id' => '$email_domain_id',
'docs' => array('$push' => '$$ROOT')
)),
array('$facet' => array(
'customLimits' => array(
array('$unwind' => '$docs'),
array('$lookup' => array(
'from' => 'email_domain_limits', // Replace with your collection name for domain-specific limits
'localField' => '_id',
'foreignField' => 'email_domain_id',
'as' => 'limitData'
)),
array('$unwind' => '$limitData'),
array('$replaceRoot' => array('newRoot' => array(
'$mergeObjects' => array('$limitData', '$$ROOT')
))),
array('$project' => array(
'docs' => array(
'$cond' => array(
array('$eq' => ['$email_domain_id', '$_id']),
'$docs',
[]
)
)
)),
array('$unwind' => '$docs'),
array('$group' => array(
'_id' => '$_id',
'docs' => array('$push' => '$docs')
)),
array('$project' => array(
'docs' => array(
'$slice' => ['$docs', 0, array('$arrayElemAt' => array([$domainLimits, '$_id'], 0))]
)
)),
),
'result' => array(
array('$skip' => (int)$unsusbcribe[$i]->skip),
array('$limit' => 10), // Default limit if no specific limit defined
),
))
);
$details = $this->mongo_db4->aggregate('opend_contacts_profile', $opn);
echo "<pre>";
print_r($details);
exit;
The problem lies in the aggregation logic, where the data should be divided into separate limits based on domain IDs. However, it seems that the current implementation is not achieving this, and the data is not being properly segmented by domain ID.
I need assistance in troubleshooting and resolving this issue. The expected outcome is to receive data in separate limits according to the specified domain ID restrictions. Any guidance or modifications to the code would be highly appreciated.