Mongo查找不包含给定值的文档(使用$ not) [英] Mongo find documents that do not contain a given value (using $not)
问题描述
我在MongoDB中有两项:
{'title':'active item',
'tags':[
{'tag':'active'},
{'tag':'anothertag'}
]}
{'title':'completed item',
'tags':[
{'tag':'completed'}
]}
它可以查找标记为已完成的项目:
db.items.find({'tags.tag':'completed'})
RESULT: [<completed item>]
现在,我想选择所有未标记为已完成的项目,所以我尝试:
db.items.find({$not:{'tags.tag':'completed'}})
DESIRED RESULT: [<active item>]
ACTUAL RESULT: []
但是以某种方式,这不会返回任何结果.显然,我在Mongo中误解了$ not,但是为什么呢?如何查询以查找标记中未包含给定值的记录?
I have two items in MongoDB: It works to find items which are tagged as completed: Now, I want to select all items which are not tagged as completed, so I tried: But somehow this doesn't return any results. Clearly I misunderstand $not in Mongo, but why? How do I query to find the records that do not contain a given value in their tags? The target of the So parvin's answer is the easiest way to do this, but just for learning purposes, you can do this with
这篇关于Mongo查找不包含给定值的文档(使用$ not)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!db.items.find({tags: {$not: {$elemMatch: {tag: 'completed'}}}})
db.items.find({'tags.tag': {$not: /completed/}})
{'title':'active item',
'tags':[
{'tag':'active'},
{'tag':'anothertag'}
]}
{'title':'completed item',
'tags':[
{'tag':'completed'}
]}
db.items.find({'tags.tag':'completed'})
RESULT: [<completed item>]
db.items.find({$not:{'tags.tag':'completed'}})
DESIRED RESULT: [<active item>]
ACTUAL RESULT: []
$not
operator needs to be an operator-expression, not a field/value object.$not
by using $not
supported expressions like:db.items.find({tags: {$not: {$elemMatch: {tag: 'completed'}}}})
db.items.find({'tags.tag': {$not: /completed/}})