Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine+MongoDB - How to query for documents with array that's not empty

I would like to receive all the documents with array "likes" with size greater than zero. I saw an example of using the ->size() method to get an array in a specific size:

$qb = $dm->createQueryBuilder('Article')->field('comments')->size(0);

but not to get an array with size different than zero, is there an option to do that?

Thank you!

like image 854
Geva Tal Avatar asked Oct 07 '22 09:10

Geva Tal


1 Answers

You can pass specific positive integers to size, but you cannot use it to query ranges. This is not a limitation of Doctrine but of MongoDB. The docs on $size say:

$size does not accept ranges of values. To select documents based on fields with different numbers of elements, create a counter field that you increment when you add elements to a field.

To do this, add a $comments_count @Int field to Article and update it either a) in document methods which modify $comments or b) in a document method annotated with @PreUpdate.

Another (inefficient) option is to use where with a javascript expression:

$where = "function() { return this.comments && this.comments.length > 0; }";
$qb = $dm->createQueryBuilder('Article')->field('comments')->where($where);
like image 110
dylan oliver Avatar answered Oct 10 '22 03:10

dylan oliver