简体   繁体   中英

Doctrine ODM - MongoDB grouping

I am trying to build Doctrine ODM query with grouping (I am fresh to Mongo, I have strong SQL background).

I want to get all results that had 2 or more displays in given time period.

public function findDisplayedForCompany(string $companyId, DateTime $start)
{
    $qb = $this->createQueryBuilder();
    $qb->field('interactor')->equals($companyId)
        ->field('interactionDate')->gte($start)
        ->group(['interacted' => 'interacted'], ['count' => 0])
        ->reduce('function (obj, prev) { prev.count++; }')
        ->field('count')
        ->gt('1');

    $query = $qb->getQuery();

    return $query->execute();
}

Unfortunately, the code above give me no results.

In SQL it will be something like SELECT *, COUNT(*) count FROM x GROUP BY interacted HAVING COUNT(*) > 1


Document structure (it's pretty simple):

class Interaction
{
/**
 * @MongoDB\Id
 */
protected $id;

/**
 * @MongoDB\ReferenceOne(targetDocument="Company", storeAs="id")
 * @var  Company
 */
protected $interacted;


/**
 * @MongoDB\ReferenceOne(targetDocument="Company", storeAs="id")
 * @var Company
 */
protected $interactor;

/**
 * @MongoDB\Field(type="date")
 * @var \DateTime
 */
protected $interactionDate;

public function __construct(Company $interacted, Company $interactor)
{
    $this->interacted = $interacted;
    $this->interactor = $interactor;
    $this->interactionDate = new \DateTime();
}
}

I found some workaround, that works for my needs, however I'm not satisfied with it, so I'm still looking for help with initial problem.

public function findDisplayedForCompany(string $companyId, $start)
{
    $qb = $this->createQueryBuilder();
    $qb->field('interactor')->equals($companyId)
        ->field('interactionDate')->gte($start)
        ->group(['company' => 'company'], ['count' => 0])
        ->reduce('function (obj, prev) { prev.count++; }');

    $query = $qb->getQuery();

    $results = $query->execute()->toArray();
    $ids = [];
    foreach ($results as $result) {
        if ($result['count'] > 1) {
            $ids[] = (string) $result['company'];
        }
    }

    return $ids;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM