Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query where not equal to null or empty

Tags:

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?

like image 974
Shreya Batra Avatar asked Jul 10 '17 08:07

Shreya Batra


People also ask

Is not null or empty in SQL query?

The IS NOT NULL condition is used in SQL to test for a non-NULL value. It returns TRUE if a non-NULL value is found, otherwise it returns FALSE. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.

How do I ignore NULL values in SELECT query?

SELECT column_names FROM table_name WHERE column_name IS NOT NULL; Query: SELECT * FROM Student WHERE Name IS NOT NULL AND Department IS NOT NULL AND Roll_No IS NOT NULL; To exclude the null values from all the columns we used AND operator.

How do you write not equal to blank in SQL?

sql - Not equal <> !=

How do I check if a column is NULL or empty in SQL?

SELECT * FROM yourTableName WHERE yourSpecificColumnName IS NULL OR yourSpecificColumnName = ' '; The IS NULL constraint can be used whenever the column is empty and the symbol ( ' ') is used when there is empty value.


1 Answers

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

like image 101
Neil Lunn Avatar answered Oct 01 '22 23:10

Neil Lunn