Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mongodb Mongo查找不包含给定值的文档(使用$not)_Mongodb - Fatal编程技术网

Mongodb Mongo查找不包含给定值的文档(使用$not)

Mongodb Mongo查找不包含给定值的文档(使用$not),mongodb,Mongodb,我在MongoDB中有两项: {'title':'active item', 'tags':[ {'tag':'active'}, {'tag':'anothertag'} ]} {'title':'completed item', 'tags':[ {'tag':'completed'} ]} 它可以查找标记为已完成的项目: db.items.find({'tags.tag':'completed'}) RESULT: [<compl

我在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({'tags.tag':'completed'})
结果:[]
现在,我想选择所有未标记为已完成的项目,因此我尝试:

db.items.find({$not:{'tags.tag':'completed'}})
DESIRED RESULT: [<active item>]
ACTUAL RESULT: []
db.items.find({$not:{'tags.tag':'completed'})
期望结果:[]
实际结果:[]
但不知何故,这并没有返回任何结果。显然我误解了$not在Mongo,但为什么?如何查询以查找标记中不包含给定值的记录?

您可以使用operator进行查询

db.items.find({"tags.tag" : {$ne : "completed"}})
运算符的目标需要是运算符表达式,而不是字段/值对象

因此,parvin的答案是实现这一点的最简单方法,但仅出于学习目的,您可以使用
$not
来实现这一点,方法是使用
$not
支持的表达式,如:

db.items.find({tags:{$not:{$elemMatch:{tag:'completed'}})
db.items.find({'tags.tag':{$not:/completed/}})

+1它可以工作,但为什么?在我的SQL背景下,我认为$ne会不正确地排除没有任何标记的项。为什么$elemMatch不做我想做的?当我第一次阅读$elemMatch的文档时,我不理解它。但您的答案清楚地说明了$elemMatch的用法。谢谢