$elemMatch:{$exists: true}

To check whether an array is empty, while in an aggregation pipeline, I would do
db.movies.aggregate([{$match: {writers: {$elemMatch: {$exists: true}}}}])

What could be my options if I have to check for the existence of multiple fields, alongisde writers?
Will, multiple $match stages have to be included for multiple fields?

I tried the following, but got an error:

2018-11-18T10:12:41.624+0530 E QUERY [js] SyntaxError: missing ] after element list @(shell):1:150`

Thanks
Apurva.

Looks like the curly braces do not match. I am not to sure that elemmatch … exists give you the expected result.

I did some experimentation with { arrayField : { $exists : true } } vs { arrayField : { $elemMatch : { ‘$exists’ : true } } }. Here are my findings:

mongo> db.arrayCollection.find()
{ “_id” : “1”, “myArray” : [ 0, 1 ] }
{ “_id” : “2”, “myArray” : [ ] }
{ “_id” : “3” }

A match with { myArray : { $exists : true } } with produce:

{ “_id” : “1”, “myArray” : [ 0, 1 ] }
{ “_id” : “2”, “myArray” : [ ] }

While { myArray : { $elemMatch : { $exists : true } } } will give:

{ “_id” : “1”, “myArray” : [ 0, 1 ] }

So the first one will gives all documents that have the array, while the second one will give all documents that have a non-empty array.

I then have to retract my previous comment since ‘elemMatch … exists …’ works.

It looks like the ‘}’ before the ‘cast:’ closes the opening curly of the ‘$match’.

3 Likes

Thank you very much @steevej-1495 for sharing your findings!!

2 Likes