How do I do a "NOT IN" query in Mongo?

MongodbDatabase

Mongodb Problem Overview


This is my document:

{ 
    title:"Happy thanksgiving",
    body: "come over for dinner",
    blocked:[
       {user:333, name:'john'},
       {user:994, name:'jessica'},
       {user:11, name: 'matt'},
    ]
}

What is the query to find all documents that do not have user 11 in "blocked"?

Mongodb Solutions


Solution 1 - Mongodb

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/

Solution 2 - Mongodb

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]}});

Solution 3 - Mongodb

Try the following:

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

This worked for me.

Solution 4 - Mongodb

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.).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTIMEXView Question on Stackoverflow
Solution 1 - MongodbJustin JenkinsView Answer on Stackoverflow
Solution 2 - MongodbAaron SilvermanView Answer on Stackoverflow
Solution 3 - MongodbkaneView Answer on Stackoverflow
Solution 4 - MongodbFemiView Answer on Stackoverflow