简体   繁体   English

Pymongo:如何在MongoDB中查询现有和非空字符串字段?

[英]Pymongo: How to query MongoDB for existing and non-empty string field?

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 字段不为NULL
  • field is not an empty string. 字段不是空字符串。

What's the best way to do that? 最好的方法是什么?

Use {'$nin': [None, '']} : 使用{'$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'}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM