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.
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 } }
]})
I did it using this :
db.event_copy.find({'channels.0' : {$exists: true}}).count()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With