使用 $exists 判断字段是否存在;2. 用 $eq 匹配 null 或结合 $exists 区分缺失与 null;3. 检查空字符串、空数组用 "" 或 $size: 0;4. 空对象可用聚合判断;5. 综合多种“空”情况用 $or 联合条件查询。
在 MongoDB 中判断字段是否为空,通常指的是判断字段是否存在、是否为 null、是否为空字符串("")、空数组([])或空对象({})。根据不同的场景,可以使用不同的查询操作符来实现。
{ "fieldName": { "$exists": true } } —— 字段存在{ "fieldName": { "$exists": false } } —— 字段不存在
email 字段的文档
db.users.find({ "email": { "$exists": true } })
db.users.find({ "email": null }) —— 匹配 email 为 null 或字段不存在的文档
db.users.find({ "email": { "$eq": null, "$exists": true } })
db.users.find({ "name": "" }) —— 简单匹配空字符串
更严格的方式(确保是字符串类型):
db.users.find({ "name": { "$type": "string", "$eq": "" } })
db.users.find({ "tags": { "$size": 0 } }) —— 匹配空数组
空(如嵌套文档 {}),可使用聚合管道:
db.users.aggregate([ { "$addFields": { "isProfileEmpty": { "$eq": [ "$profile", {} ] } }}, { "$match": { "isProfileEmpty": true } }])
db.users.find({ "$or": [ { "status": { "$exists": false } }, { "status": null }, { "status": "" }, { "status": { "$size": 0 } } ]})
基本上就这些常见用法。根据你的数据结构选择合适的方式,尤其是注意区分“字段不存在”和“字段为空值”的需求。