Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

mongodb - Mongo find documents that do not contain a given value (using $not)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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/}})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...