在mongodb和pymongo中测试空字符串 [英] Test empty string in mongodb and pymongo

查看:86
本文介绍了在mongodb和pymongo中测试空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的数据结构.

[{
"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中测试空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆