问题描述
这似乎是一个简单的问题,但我还没有找到答案:我正在使用MongoDB,我想执行一个查询,在其中提供搜索条件,但是我也想解决一个例外,即根据条件排除某些文档.例如,想象一个具有字段name
,age
和gender
的集合.
This seems like a simple enough question but I haven't found an answer:I'm using MongoDB and I want to perform a query in which I provide search criteria, but I also want to carve out an exception where certain documents are excluded based on criteria. For example, imagine a collection with the fields name
, age
and gender
.
是否正在检索特定年龄以下的所有人?容易:<collection>.find({'age':{'$lt':<maxAge>}})
检索特定年龄以下的所有女性?小菜一碟:<collection>.find({'gender':female, 'age':{'$lt':<maxAge>}})
Retrieving everyone below a certain age? Easy: <collection>.find({'age':{'$lt':<maxAge>}})
Retrieving all females below a certain age? Piece of cake: <collection>.find({'gender':female, 'age':{'$lt':<maxAge>}})
但是如何检索所有人,除非他们是[女性且未满一定年龄的人]?您可以使用'$ ne'运算符轻松否定特定字段,但是我该如何否定所有符合一组条件的人呢?
But what about retrieving everyone, except if they are [female and below a certain age?]. You can easily negate a specific field with the '$ne' operator, but how do I negate everyone who matches a set of criteria?
推荐答案
您必须应用布尔逻辑,才能将AND分别转换为每个项的否定的OR:
You would have to apply boolean logic to invert the AND into an OR of the negation of each term individually:
collection.find({$or: [{age: {$gte: maxAge}}, {gender: {$ne: 'female'}}]})
或
collection.find({$or: [{age: {$not: {$lt: maxAge}}}, {gender: {$ne: 'female'}}]})
这篇关于如何指定从查询中排除文档的条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!