答案:查询字段不为空需根据“空”的定义选择方法。常用方式包括:使用 $ne 排除 null 值;结合 $and 或 $exists 与 $ne 排除 null 和空字符串;通过 $type 判断数据类型并排除空值;对数组或对象字段使用 $ne 与 [] 或 {} 比较。例如查 email 非空:db.users.find({ email: { $exists: true, $ne: null, $ne: "" } }),确保字段存在且不为 null 或空字符串,适用于多数场景。

在 MongoDB 中,查询某个字段不为空的情况,通常有几种常见写法,具体取决于“空”的定义(比如是 null、空字符串、空数组,还是不存在字段)。以下是常用的查询方式:
$ne(not equal)排除 null 值,并确保字段存在:
{ "fieldName": { $ne: null } }
fieldName 存在且值不是 null 的文档。
null 和空字符串:
{ "fieldName": { $ne: null, $ne: "" } }
$ne 直接并列生效,更推荐用 $and 或检查类型。
更稳妥的写法:
{ $and: [ { "fieldName": { $ne: null } }, { "fieldName": { $ne: "" } } ] }
{ "fieldName": { $exists: true, $ne: "" } }
{ "fieldName": { $type: "string", $ne: "" } }
{ "fieldName": { $exists: true, $ne: [] } }
{ "fieldName": { $exists: true, $ne: {} } }
db.users.find({ email: { $exists: true, $ne: null, $ne: "" } })
基本上就这些。根据你的数据结构选择合适的方式,关键是明确“空”指的是哪些情况。
以上就是mongodb查询不为空怎么写?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号