筛选非空字段需结合$exists、$ne和$regex等操作符,正确写法为:db.collection.find({ fieldName: { $exists: true, $ne: null, $ne: "", $regex: /\S/ }}),确保字段存在、非null、非空字符串且含有效字符。

在 MongoDB 中,筛选“不等于空”的字段,需要根据“空”的具体含义来选择查询条件。常见的“空”包括:空字符串 ""、null、空数组 []、空对象 {} 等。以下是几种常见场景及对应的查询方法。
示例:筛选 name 字段不为 null 且不为空字符串的文档
db.collection.find({
name: { $ne: null, $ne: "" }
})✅ 正确写法:
db.collection.find({
$and: [
{ name: { $ne: null } },
{ name: { $ne: "" } }
]
})db.collection.find({
name: { $exists: true, $ne: null, $ne: "" }
})db.collection.find({
name: { $exists: true, $ne: null },
name: { $ne: "" }
})db.collection.find({
name: { $exists: true, $ne: null, $not: { $eq: "" } }
})筛选非空数组:
db.collection.find({
tags: { $exists: true, $ne: [], $ne: null }
})筛选非空对象:
db.collection.find({
profile: {
$exists: true,
$ne: null,
$ne: {}
}
})db.collection.find({
name: { $regex: /\S/ } // 至少包含一个非空白字符
})db.collection.find({
fieldName: {
$exists: true,
$ne: null,
$ne: "",
$regex: /\S/
}
})基本上就这些。根据你的数据结构选择合适的方式即可。
以上就是mongodb如何筛选不等于空的字段的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号