Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find MongoDB records where array field is not empty

All of my records have a field called "pictures". This field is an array of strings.

I now want the newest 10 records where this array IS NOT empty.

I've googled around, but strangely enough I haven't found much on this. I've read into the $where option, but I was wondering how slow that is to native functions, and if there is a better solution.

And even then, that does not work:

ME.find({$where: 'this.pictures.length > 0'}).sort('-created').limit(10).execFind() 

Returns nothing. Leaving this.pictures without the length bit does work, but then it also returns empty records, of course.

like image 875
skerit Avatar asked Feb 09 '13 15:02

skerit


People also ask

How do I query an array field in MongoDB?

To query if the array field contains at least one element with the specified value, use the filter { <field>: <value> } where <value> is the element value. To specify conditions on the elements in the array field, use query operators in the query filter document: { <array field>: { <operator1>: <value1>, ... } }

How do I query a nested field in MongoDB?

Query on Nested Field To specify a query condition on fields in an embedded/nested document, use dot notation ( "field. nestedField" ). When querying using dot notation, the field and nested field must be inside quotation marks.

Does MongoDB preserve array order?

yep MongoDB keeps the order of the array.. just like Javascript engines..


2 Answers

If you also have documents that don't have the key, you can use:

ME.find({ pictures: { $exists: true, $not: {$size: 0} } }) 

MongoDB doesn't use indexes if $size is involved, so here is a better solution:

ME.find({ pictures: { $exists: true, $ne: [] } }) 

If your property can have invalid values (like null boolean or others) , then you an add an additional check using $types as proposed in this answer:

With mongo >= 3.2:

ME.find({ pictures: { $exists: true, $type: 'array', $ne: [] } }) 

With mongo < 3.2:

ME.find({ pictures: { $exists: true, $type: 4, $ne: [] } }) 

Since the MongoDB 2.6 release, you can compare with the operator $gt, but this could lead to unexpected results (you can find a detailed explanation in this answer):

ME.find({ pictures: { $gt: [] } }) 
like image 116
Chris' Avatar answered Sep 24 '22 21:09

Chris'


After some more looking, especially in the mongodb documents, and puzzling bits together, this was the answer:

ME.find({pictures: {$exists: true, $not: {$size: 0}}}) 
like image 21
skerit Avatar answered Sep 24 '22 21:09

skerit