在mongodb和pymongo中测试空字符串

编程入门 行业动态 更新时间:2024-10-26 14:26:59
本文介绍了在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中测试空字符串

本文发布于:2023-10-08 13:55:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1472829.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:测试   空字符串   mongodb   pymongo

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!