31

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?

1
  • Thanks a lot dude! It worked. Even i suspected the same thing as soon as i posted the question that it's somehow because of the two $ne. Commented Jul 10, 2017 at 8:44

1 Answer 1

74

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".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.