Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test empty string in mongodb and pymongo

Here is my data structure.

[{ "name": "David", "lastname": "", }, { "name": "Angela" }] 

"lastname" is sometimes present and sometimes not and sometime is "".

I want to get all rows that have lastname not equal to "". But this does not work. It returns both the rows when lastname is "" and when lastname is not present at all. in the example above I want to only get the David node.

db.collection.find( {"lastname": {"$ne": ""}} ) 
like image 370
David Dehghan Avatar asked Mar 14 '12 00:03

David Dehghan


People also ask

IS NULL check in MongoDB?

MongoDB fetch documents containing 'null' If we want to fetch documents from the collection "testtable" which contains the value of "interest" is null, the following mongodb command can be used : >db. testtable. find( { "interest" : null } ).

How do I search for a string in MongoDB?

Use the $text query operator to perform text searches on a collection with a text index. $text will tokenize the search string using whitespace and most punctuation as delimiters, and perform a logical OR of all such tokens in the search string.

How does empty string work?

An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null .


2 Answers

db.collection.find({"lastname" : {"$exists" : true, "$ne" : ""}}) 

In the mongo shell (id's omitted to save space)

> db.collection.find()   { "name" : "Angela" }   { "name" : "David", "lastname" : "" }   { "name" : "Kyle",  "lastname" : "Test" }   { "name" : "John",  "lastname" : null }  > db.collection.find({"lastname" : {"$exists" : true, "$ne" : ""}})   { "name" : "Kyle", "lastname" : "Test" }   { "name" : "John",  "lastname" : null } 

In case you also want to filter out matches against null values you need to adjust the criteria as follows (we can also get rid of $exists as "$ne": null takes care of this)

> db.collection.find({$and:[{"lastname": {"$ne": null}}, {"lastname": {"$ne": ""}}]})   { "name" : "Kyle", "lastname" : "Test" } 
like image 136
Kyle Avatar answered Oct 16 '22 07:10

Kyle


Facing this problem I thought in another solution:

db.collection.find({"lastname": {"$gte": " "}}) 

With this I could get only the not empty strings, also ignoring null and not existent field, because any printable value (ASCII) has a greater value than space (32).

https://en.wikipedia.org/wiki/ASCII

like image 40
Joao Roberto joaogameprog Avatar answered Oct 16 '22 06:10

Joao Roberto joaogameprog