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?

1 Answer 1

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'}]

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.