Pi Horse
Pi Horse

Reputation: 2440

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.

Upvotes: 9

Views: 51430

Answers (4)

Abhijit Manepatil
Abhijit Manepatil

Reputation: 957

from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017/')
db = client['my_database']
col=db['my_collection']

### Input
email="[email protected]"
########
exist_count=col.find({"email": email},{'_id':0}).count()

if exist_count>=1:
    print("Field value is present")
else:
    print("Field value is not present")

Upvotes: 0

Neil Lunn
Neil Lunn

Reputation: 151220

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 } }
]})

Upvotes: 17

Pi Horse
Pi Horse

Reputation: 2440

I did it using this :

db.event_copy.find({'channels.0' : {$exists: true}}).count()

Upvotes: 4

Anand Jayabalan
Anand Jayabalan

Reputation: 12944

Check out the size operator here

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

Upvotes: 1

Related Questions