Reputation: 17359
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:
What's the best way to do that?
Upvotes: 0
Views: 2198
Reputation: 17359
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'}]
Upvotes: 5