使用 $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 是最直接的方式。
注意字段是否存在,避免 null 值导致意外结果,必要时可加上字段存在性判断:{ description: { $exists: true }, ... }
基本上就这些。MongoDB 不支持像 SQL 中的 NOT LIKE 直接语法,但通过 $not 和正则可以灵活实现不包含字符串的查询。操作不复杂但容易忽略大小写和性能问题。