Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"?

like image 279
TIMEX Avatar asked Jun 17 '11 20:06

TIMEX


People also ask

How write not query in MongoDB?

MongoDB provides different types of comparison query operators and $nin (not in) operator is one of them. This operator is used to select those documents where the value of the field is not equal to any of the given value in the array and the field that does not exist.

How do I exclude fields in MongoDB?

To exclude the _id field from the output documents of the $project stage, specify the exclusion of the _id field by setting it to 0 in the projection document.

What is $Nin in MongoDB?

$nin selects the documents where: the field value is not in the specified array or. the field does not exist.

IS NOT NULL check in MongoDB?

To query for is not null value, we can use the $ne operator as well as the $eq operator and specify the desired value that we want to query for. This guide aims to provide readers with different ways and examples for the same to query for is not null values in MongoDB.


2 Answers

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/

like image 109
Justin Jenkins Avatar answered Oct 28 '22 15:10

Justin Jenkins


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]}}); 
like image 25
Aaron Silverman Avatar answered Oct 28 '22 14:10

Aaron Silverman