问题描述
我在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,但是为什么呢?如何查询以查找标记中未包含给定值的记录?
$not
运算符必须是运算符表达式,而不是字段/值对象.
因此,parvin的答案是执行此操作的最简单方法,但仅出于学习目的,您可以使用$not
支持的表达式,例如
{'title':'active item',
'tags':[
{'tag':'active'},
{'tag':'anothertag'}
]}
{'title':'completed item',
'tags':[
{'tag':'completed'}
]}
来实现此目的:
db.items.find({tags: {$not: {$elemMatch: {tag: 'completed'}}}})
db.items.find({'tags.tag': {$not: /completed/}})
I have two items in MongoDB:
{'title':'active item',
'tags':[
{'tag':'active'},
{'tag':'anothertag'}
]}
{'title':'completed item',
'tags':[
{'tag':'completed'}
]}
It works to find items which are tagged as completed:
db.items.find({'tags.tag':'completed'})
RESULT: [<completed item>]
Now, I want to select all items which are not tagged as completed, so I tried:
db.items.find({$not:{'tags.tag':'completed'}})
DESIRED RESULT: [<active item>]
ACTUAL RESULT: []
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 $not
operator needs to be an operator-expression, not a field/value object.
So parvin's answer is the easiest way to do this, but just for learning purposes, you can do this with $not
by using $not
supported expressions like:
db.items.find({tags: {$not: {$elemMatch: {tag: 'completed'}}}})
db.items.find({'tags.tag': {$not: /completed/}})
这篇关于Mongo查找不包含给定值的文档(使用$ not)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!