Mongo查找不包含给定值的文档(使用$ not) [英] Mongo find documents that do not contain a given value (using $not)

查看:122
本文介绍了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,但是为什么呢?如何查询以查找标记中未包含给定值的记录?

解决方案

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆