如何用MongoDB Atlas Search实现类似find中$ne:True的查询?
用Atlas Search实现
$ne: true的等价逻辑 你可以通过Atlas Search的**复合查询(compound)**结合mustNot和equals操作符来实现需求,核心思路是排除所有active字段值为true的文档,剩下的自然就是字段不存在或值为false的文档,和你用普通find时{'active': {'$ne': true}}的逻辑完全一致。
具体聚合查询示例:
db.your_collection.aggregate([ { $search: { compound: { mustNot: [ { equals: { path: "active", value: true } } ] } } } ])
逻辑说明:
compound.mustNot会过滤掉所有匹配子条件的文档,这里的子条件是active字段等于true- 剩下的文档包含两种情况:要么
active字段根本不存在,要么active字段存在但值为false,完全符合你的需求
如果需要和其他搜索条件组合(比如同时匹配某个关键词),只需要把额外条件加到compound.must数组里即可,比如:
db.your_collection.aggregate([ { $search: { compound: { must: [ { text: { query: "some keyword", path: "content" } } ], mustNot: [ { equals: { path: "active", value: true } } ] } } } ])
内容的提问来源于stack exchange,提问作者shraddha
相关产品推荐
相关产品推荐

