Note that a future version of MongoDB will include the expression $isArray aggregation . Meanwhile...
... the following code will do the trick, since the $elemMatch only matches documents that have an array field:
> db.test.find({"ax": 1, "a": {$not: {$elemMatch: {x:1}}}})
Given this dataset:
> db.test.find({},{_id:0}) { "a" : { "x" : 1 } } { "a" : [ { "x" : 1 } ] } { "a" : [ { "x" : 0 }, { "x" : 1 } ]
He will return:
> db.test.find({"ax": 1, "a": {$not: {$elemMatch: {x:1}}}}, {_id:0}) { "a" : { "x" : 1 } }
Please note that this should be considered as a short-term solution. The MongoDB team made sure that [{x:1}] and {x:1} behave the same way (see dot-notation or $type for arrays ). Therefore, you should think that at some point in the future $elemMatch may be updated (see Question JIRA SERVER-6050 ). In the meantime, it might be worth considering fixing your data model, so you would no longer need to distinguish between an array containing one subdocument and a bare subdocument.
source share