Shreya Batra
Shreya Batra

Reputation: 800

Query where not equal to null or empty

I am trying to find all the documents where email exists.

I am trying the following find query:

{ "email": {$exists:true, $ne:null, $ne:""}}

Still I am getting documents where email is null.

Can anyone tell me what I am doing wrong?

Upvotes: 31

Views: 46522

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151112

You want $nin here:

.find({ "email": { "$nin": [ null, "" ] } })

The problem is $ne is repeated twice and overwrites. You could use $or but $nin is shorter:

Given:

{
    "_id" : ObjectId("59633c28f5f11516540d118e"),
    "a" : 1.0
}
{
    "_id" : ObjectId("59633c28f5f11516540d118f"),
    "a" : 1.0,
    "email" : ""
}
{
    "_id" : ObjectId("59633c28f5f11516540d1190"),
    "a" : 1.0,
    "email" : null
}
{
    "_id" : ObjectId("59633c28f5f11516540d1191"),
    "a" : 1.0,
    "email" : "fred"
}

Just returns:

{
    "_id" : ObjectId("59633c28f5f11516540d1191"),
    "a" : 1.0,
    "email" : "fred"
}

Also you do not also need $exists when you are actually testing a value. It's already implied that is does "exist".

Upvotes: 74

Related Questions