使用 $not 和 $regex 可查询字段不包含特定字符串的文档,如 db.collection.find({ description: { $not: /error/ } });忽略大小写时添加 i 标志,如 /error/i;可结合其他条件组合查询,注意性能影响及 null 值处理。

在 MongoDB 中,如果你想查询某个字段不包含特定字符串的文档,可以使用 $not 和 $regex 操作符组合来实现。
description 字段不包含"error"这个字符串的所有文档:
db.collection.find({
description: { $not: /error/ }
})
或者使用 $regex 显式写法:
db.collection.find({
description: { $not: { $regex: 'error' } }
})
i 标志:
db.collection.find({
description: { $not: /error/i }
})
或等价写法:
db.collection.find({
description: { $not: { $regex: 'error', $options: 'i' } }
})
db.logs.find({
status: "active",
log: { $not: { $regex: 'timeout' } }
})
$not + $regex 是最直接的方式。{ description: { $exists: true }, ... }
基本上就这些。MongoDB 不支持像 SQL 中的 NOT LIKE 直接语法,但通过 $not 和正则可以灵活实现不包含字符串的查询。操作不复杂但容易忽略大小写和性能问题。
以上就是mongodb如何查询不包含某个字符串的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号