user2105469
user2105469

Reputation: 1433

Testing for empty arrays in Mongodb

I'm looking for documents that have both 'e-campaigns' and 'p-campaigns' arrays that are non-empty:

 db.coll.find( { 'p-campaigns':{$ne:[]} ,  'e-campaigns' : {$ne:[]} }     )

I run the query on each array separately and do find docs with non-empty p-campaigns and e-campaigns, but the combined conditions turns out empty. I know there are documents with both p-campaigns and e-campaigns non-empty. I've tried using $and, with the same result: no docs with both arrays non-empty.

Am I going about this the right way? If not, why? This seems like the logical way to run this query on the conditions above. Thanks.

Upvotes: 0

Views: 83

Answers (2)

Praveen Kumar Verma
Praveen Kumar Verma

Reputation: 3510

For empty array in mongoDb filter query:

{field: {$size: 0}} // When find field array size is 0 or empty.

Upvotes: 0

Artem Mezhenin
Artem Mezhenin

Reputation: 5757

Here is my variant:

> db.a.save({x:[], y:[]})
> db.a.save({x:[1], y:[]})
> db.a.save({x:[], y:[1]})
> db.a.save({x:[1], y:[1]})
> db.a.find()
{ "_id" : ObjectId("52248f5efb41276d1f3e3164"), "x" : [ ], "y" : [ ] }
{ "_id" : ObjectId("52248f61fb41276d1f3e3165"), "x" : [ 1 ], "y" : [ ] }
{ "_id" : ObjectId("52248f66fb41276d1f3e3166"), "x" : [ ], "y" : [ 1 ] }
{ "_id" : ObjectId("52248f69fb41276d1f3e3167"), "x" : [ 1 ], "y" : [ 1 ] }
> db.a.find({ 'x':{$ne:[]} ,  'y' : {$ne:[]} })
{ "_id" : ObjectId("52248f69fb41276d1f3e3167"), "x" : [ 1 ], "y" : [ 1 ] }

Upvotes: 1

Related Questions