Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB - Check if value exists for a field in a document

I have a collection where the document looks like below:

/* 0 */

{
    "_id" : ObjectId("5320b1c723bc746084fa7107"),
    "channels" : [ 
        3, 
        4
    ]
}


/* 1 */

{
    "_id" : ObjectId("5320b1c723bc746084fa7107"),
    "channels" : [ ]
}

I want to form a query such that I want all documents where channels has some value and is not empty.

I tried this:

db.event_copy.find({"channels":{$exists:true}})

But that will still return me the documents with no values in channel.

like image 489
Pi Horse Avatar asked Mar 13 '14 01:03

Pi Horse


2 Answers

You need the $size operator. To find something with no elements do the following

db.collection.find({ channels: {$size: 0} })

If you know you have a fixed size then do that

db.collection.find({ channels: {$size: 2} })

Otherwise reverse that with $not

db.collection.find({ channels: {$not:{$size: 0}} })

And you can combine with $and:

db.collection.find({ $and: [ 
    { channels: {$not:{$size: 0}} },
    { channels: {$exists: true } }
]})
like image 167
Neil Lunn Avatar answered Sep 28 '22 01:09

Neil Lunn


I did it using this :

db.event_copy.find({'channels.0' : {$exists: true}}).count()
like image 40
Pi Horse Avatar answered Sep 27 '22 23:09

Pi Horse