mongodb查询不为空怎么写?

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

在 MongoDB 中,查询某个字段不为空的情况,通常有几种常见写法,具体取决于“空”的定义(比如是 null、空字符串、空数组,还是不存在字段)。以下是常用的查询方式:

1. 字段存在且不为 null

使用 $ne(not equal)排除 null 值,并确保字段存在:

{ "fieldName": { $ne: null } }

这会匹配 fieldName 存在且值不是 null 的文档。

2. 排除空字符串

如果字段可能是空字符串,可以同时排除 null 和空字符串:

{ "fieldName": { $ne: null, $ne: "" } }

注意:MongoDB 不支持在同一个字段上多个 $ne 直接并列生效,更推荐用 $and 或检查类型。 更稳妥的写法:

{ $and: [ { "fieldName": { $ne: null } }, { "fieldName": { $ne: "" } } ] }

3. 使用 $exists 和 $type 排除无效值

确保字段存在,且是字符串类型(避免其他类型干扰)且非空:

{ "fieldName": { $exists: true, $ne: "" } }

或者结合类型判断:

{ "fieldName": { $type: "string", $ne: "" } }

4. 排除空数组或空对象

如果字段是数组,想查非空数组:

{ "fieldName": { $exists: true, $ne: [] } }

如果是对象类型且非空:

{ "fieldName": { $exists: true, $ne: {} } }

综合示例

假设要查 users 集合中 email 字段存在、不为 null、也不是空字符串

db.users.find({ email: { $exists: true, $ne: null, $ne: "" } })

这是最常用也最安全的写法。

基本上就这些。根据你的数据结构选择合适的方式,关键是明确“空”指的是哪些情况。