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

前端 未结 4 1239
花落未央
花落未央 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]}});
    
    0 讨论(0)
  • 2020-11-28 10:58

    You can use $in or $nin for "not in"

    Example ...

    > db.people.find({ crowd : { $nin: ["cool"] }});
    

    I put a bunch more examples here: http://learnmongo.com/posts/being-part-of-the-in-crowd/

    0 讨论(0)
  • 2020-11-28 11:03

    See http://docs.mongodb.org/manual/reference/operator/query/nin/#op._S_nin

    db.inventory.find( { qty: { $nin: [ 5, 15 ] } } )
    

    This query will select all documents in the inventory collection where the qty field value does not equal 5 nor 15. The selected documents will include those documents that do not contain the qty field.

    If the field holds an array, then the $nin operator selects the documents whose field holds an array with no element equal to a value in the specified array (e.g. , , etc.).

    0 讨论(0)
  • 2020-11-28 11:06

    Try the following:

    db.stack.find({"blocked.user":{$nin:[11]}})
    

    This worked for me.

    0 讨论(0)
提交回复
热议问题