本文介绍了Mongo查找不包含给定值的文档(使用$ 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,但是为什么呢?如何查询以查找标记中未包含给定值的记录?

解决方案

$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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 22:59