Reputation: 800
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
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