Test empty string in mongodb and pymongo

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


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