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

前端 未结 2 425
不知归路
不知归路 2020-12-06 11:10

I have two items in MongoDB:

{\'title\':\'active item\',
 \'tags\':[
        {\'tag\':\'active\'},
        {\'tag\':\'anothertag\'}
]}
{\'title\':\'completed         


        
相关标签:
2条回答
  • You can do it with $ne operator.

    db.items.find({"tags.tag" : {$ne : "completed"}})
    
    0 讨论(0)
  • 2020-12-06 12:03

    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/}})
    
    0 讨论(0)
提交回复
热议问题