You can use the $ size operator to query for the size of the array. Consider the following example using the JS shell:
> db.foo.drop() > db.foo.insert({_id: 1, x:[1,2]}); > db.foo.insert({_id: 2, x:[]}); > db.foo.insert({_id: 3, x:3}); > db.foo.find({x: {$size: 0}}) { "_id" : 2, "x" : [ ] } > db.foo.find({x: {$size: 1}}) > db.foo.find({x: {$size: 2}}) { "_id" : 1, "x" : [ 1, 2 ] } > db.foo.find({x: {$not: {$size: 2}}}) { "_id" : 2, "x" : [ ] } { "_id" : 3, "x" : 3 } > db.foo.find({x: {$not: {$size: 0}}}) { "_id" : 1, "x" : [ 1, 2 ] } { "_id" : 3, "x" : 3 }
I am not familiar with Mongoid, but I found an example using $size in this documentation .
Two caveats with $size are that it cannot use an index (possibly other parts of the query), and it cannot be used in range queries. If you do not mind additional bookkeeping, a viable option is to save the size of the array in a separate field (probably indexed) and query it in any way.
source share