在 mongodb 和 pymongo 中测试空字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9694223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 12:31:09  来源:igfitidea点击:

Test empty string in mongodb and pymongo

mongodbpymongo

提问by David Dehghan

Here is my data structure.

这是我的数据结构。

[{
"name": "David",
"lastname": "",
},
{
"name": "Angela"
}]

"lastname" is sometimes present and sometimes not and sometime is "".

“姓氏”有时存在,有时不存在,有时是“”。

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.

我想获取所有姓氏不等于“”的行。但这不起作用。当 lastname 为 "" 和 lastname 根本不存在时,它返回两行。在上面的示例中,我只想获取 David 节点。

db.collection.find( {"lastname": {"$ne": ""}} )

回答by Kyle

db.collection.find({"lastname" : {"$exists" : true, "$ne" : ""}})

In the mongo shell (id's omitted to save space)

在 mongo shell 中(省略 id 以节省空间)

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

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)

如果您还想过滤掉空值的匹配项,您需要按如下方式调整条件(我们也可以将 $exists 去掉为“$ne”:null 会处理这个问题)

> db.collection.find({$and:[{"lastname": {"$ne": null}}, {"lastname": {"$ne": ""}}]})
  { "name" : "Kyle", "lastname" : "Test" }

回答by Marcos Godinho

You can use a regex query:

您可以使用正则表达式查询:

db.test.find({ "lastname": /(.|\s)*\S(.|\s)*/ })

db.test.find({ "lastname": /(.|\s)*\S(.|\s)*/ })

This regex matches strings beginning or ending with 0 or N whitespaces (.|\s)and it have to be one or more non-whitespaces \Sin the middle.

此正则表达式匹配以 0 或 N 个空格开头或结尾的字符串,并且中间(.|\s)必须是一个或多个非空格\S