Question

I am trying to create a query, using the doctrine ODM query builder, where a referenced association (eventListeners) is not empty - or the collection has one or more item.

The query:

$qb = $om->createQueryBuilder(FormService::ENTITY_CLASS_NAME_FORM);
$query = $qb->field('website.$id')->equals(new \MongoId($website->getId()))
            ->field('status.name')->equals(FormService::STATUS_PUBLISHED)
            ->field('eventListeners')->notEqual(array());
            ->getQuery();
$results = $query->execute();

I've been creative in my attempts with the API; This line is clearly incorrect as it still returns all the documents regardless

->field('eventListeners')->notEqual(array());

I can see in the documentation you can use field('eventListeners')->size(3); however I do not know in advance what the collection size should be.

How do you query for non empty collections using Doctrine ODM?

Was it helpful?

Solution

It's probably not the best way to achieve this, but it does work:

$qb = $om->createQueryBuilder(FormService::ENTITY_CLASS_NAME_FORM);
$query = $qb->field('website.$id')->equals(new \MongoId($website->getId()))
            ->field('status.name')->equals(FormService::STATUS_PUBLISHED)
            ->field('eventListeners.0')->exists(true)
            ->getQuery();

$results = $query->execute();

This assumes that it is a 0 based index Collection and not a Hash.

I realise you can do DB.find({eventListeners: {$not: {$size: 0}}}) in mongo, but I'm not sure how to properly structure it in the ODM query builder.

After reviewing the odm documentation I'm not sure if it's even possible to do.

The other approach is to use a $where function: http://docs.mongodb.org/manual/reference/operator/query/where/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top