这是我的数据结构.
[{ "name": "David", "lastname": "", }, { "name": "Angela" }]姓氏"有时存在,有时不存在,有时是".
"lastname" is sometimes present and sometimes not and sometime is "".
我想获取姓氏不等于"的所有行.但这是行不通的.当姓氏为"或根本不存在姓氏时,它将返回两行.在上面的示例中,我只想获取David节点.
I want to get all rows that have lastname not equal to "". But this does not work. It returns both the rows when lastname is "" and when lastname is not present at all. in the example above I want to only get the David node.
db.collection.find( {"lastname": {"$ne": ""}} )推荐答案
db.collection.find({"lastname" : {"$exists" : true, "$ne" : ""}})
在mongo shell中(省略ID以节省空间)
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 }如果您还想过滤出符合null值的匹配项,则需要按以下方式调整条件(我们也可以将$ exists替换为"$ ne":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" }更多推荐
在mongodb和pymongo中测试空字符串
发布评论