Just an update on how to get distinct results based on search query. i did a lot of research on this and decided to share.
I hope this code will help others to achive needed results.
- You will need to use Database adapter for the new MongoDB extension library from incubator 2.1 and add custom code inside your collection.
in my case i did it like this. In my Products collection i created static method findDistinctBySearch
<?php
use Phalcon\Mvc\MongoCollection;
class Products extends MongoCollection
{
public $storeId;
public $title;
public static function findDistinctBySearch($fieldName,$filter=[],$options = [])
{
$className = get_called_class();
/** @var MongoCollection $collection */
$collection = new $className();
$connection = $collection->getConnection();
return $connection->selectCollection($collection->getSource())->distinct($fieldName, $filter, $options);
}
}
Search by title, distinct by 'storeId' and limit by 2
$options = [
'limit' => 2
];
$search = [
'title' => 'Galaxy 14 Tanning Bed'
];
$distinct = Products::findDistinctBySearch('storeId', $search, $options);
Another example with full text search
$search['$text'] = ['$search' => 'Search Query'];
$options["projection"] = ['score' => ['$meta' => "textScore"]];
$options["sort"] = ["score" => ['$meta' => "textScore"]];
$options["limit"] = 2;
$distinct = Products::findDistinctBySearch('storeId',$search,$options);