mongodb,如何在查询中使用$not filter

mongodb, how to use $not filter in query

我在 mongodb 罗盘中尝试 运行 应该是一个相当简单的查询:

{ $and: [ { Source: "hostname" }, { Message: { $not: /.*unexpected data.*1234.*/ } } ] }

基本上,我的文档模型包含一个 Source 字段和一个 Message 字段。

我需要查询来源等于给定 "hostname" 且消息不包含 "unexpected data...1234"

的所有文档

当我不在正则表达式中包含 $not 过滤器时,一切正常...所以我得到了包含此消息的所有文档...但现在我需要所有其他不包含此消息的消息包含...我不知道如何正确使用 $not。

MongoDb 手册中给出的示例仅显示了将 $not 与一个语句一起使用...但出于某种原因,即使这对我也不起作用...

{ Message: { $not: /.*unexpected data.*1234.*/ } }

同样,没有 $not 也能正常工作...我错过了什么?

编辑:

这是我正在谈论的图像,将此过滤器放在 MongoDb Compass 中,它表明过滤器不正确... MongoDb Compass 出于某种原因不能运行宁复杂过滤器?

请尝试使用应该有效的 $regex:

find( { $and: [ { Source: "hostname" }, { Message: { $not: { $regex: /.*unexpected data.*1234.*/ } } } ] })

MongoDB Compass 只支持用单引号括起来的正则表达式,不支持正斜杠。所以 $regex: /.*unexpected data.*1234.*/ 应该是 $regex: '.*unexpected data.*1234.*'.

https://jira.mongodb.org/browse/COMPASS-2993