How do I do a “NOT IN” query in Mongo?

前端 未结 4 1244
花落未央
花落未央 2020-11-28 10:15

This is my document:

{ 
    title:\"Happy thanksgiving\",
    body: \"come over for dinner\",
    blocked:[
       {user:333, name:\'john\'},
       {user:99         


        
4条回答
  •  失恋的感觉
    2020-11-28 10:57

    Since you are comparing against a single value, your example actually doesn't need a NOT IN operation. This is because Mongo will apply its search criteria to every element of an array subdocument. You can use the NOT EQUALS operator, $ne, to get what you want as it takes the value that cannot turn up in the search:

    db.myCollection.find({'blocked.user': {$ne: 11}});
    

    However if you have many things that it cannot equal, that is when you would use the NOT IN operator, which is $nin. It takes an array of values that cannot turn up in the search:

    db.myCollection.find({'blocked.user': {$nin: [11, 12, 13]}});
    

提交回复
热议问题