0

This is a great answer to the question "how to query for an existing and non-null field". But I also need to check that a field is not an empty string. So the complete query needs to check that:

  • field exists
  • field is not NULL
  • field is not an empty string.

What's the best way to do that?

Dennis Golomazov
  • 16,269
  • 5
  • 73
  • 81

1 Answers1

4

Use {'$nin': [None, '']}:

col.insert({})
col.insert({'test_field': None})
col.insert({'test_field': ''})
col.insert({'test_field': 'value'})

list(col.find({'test_field': {'$exists': True}}))
 [{u'_id': ObjectId('5b293fa7b5b55217c9afe7d0'), u'test_field': None},
  {u'_id': ObjectId('5b293fb1b5b55217c9afe7d2'), u'test_field': u''},
  {u'_id': ObjectId('5b293fb6b5b55217c9afe7d3'), u'test_field': u'value'}]

list(col.find({'test_field': {'$ne': None}}))
 [{u'_id': ObjectId('5b293fb1b5b55217c9afe7d2'), u'test_field': u''},
  {u'_id': ObjectId('5b293fb6b5b55217c9afe7d3'), u'test_field': u'value'}]

list(col.find({'test_field': {'$nin': [None, '']}}))
 [{u'_id': ObjectId('5b293fb6b5b55217c9afe7d3'), u'test_field': u'value'}]
Dennis Golomazov
  • 16,269
  • 5
  • 73
  • 81