The NOT IN Comparison Operator in MongoDB

Mehvish Ashiq Jun 07, 2022
  1. the $nin (NOT IN) Comparison Operator in MongoDB
  2. Use the $nin Operator With the find() Method to Query a Field in MongoDB
  3. Use the $nin Operator With the find() Method to Query an Embedded Document in MongoDB
  4. Use the $nin Operator With the find() Method to Query an Array in MongoDB
  5. Use the $nin Operator With the find() Method to Query an Array of Documents in MongoDB
  6. Use the $nin Comparison Operator With the update() Method to Update a Field Value in MongoDB
  7. Use the $nin Operator With Regular Expressions in MongoDB
The NOT IN Comparison Operator in MongoDB

Comparison operators are very useful while working with large datasets. It is helpful to get insights from the data.

This tutorial educates about using the $nin (NOT IN) comparison operator in MongoDB.

It also shows how to use the $nin with find() and update() methods in MongoDB. Further, we will also learn the use of regular expressions with the $nin operator.

the $nin (NOT IN) Comparison Operator in MongoDB

The $nin is one of the comparison operators in MongoDB. This operator selects those documents where the field value does not belong to the specified array, or the field does not exist.

In case the field holds an array, array of documents or array of embedded documents, then we will only get those documents where the field holds the array with no item equal to the value in the given array (we will see this scenario as well later in this tutorial).

Before digging into more details, let’s create the sample collection having some documents.

Example Code:

db.createCollection('students');
db.students.insertMany([
    {
        "name": {first: "Mehvish", last: "Ashiq"},
        "age": 30,
        "gender": "Female",
        "discipline": "BSCS",
        "joining_year": 2014,
        "department": "Computer Science",
        "courses":[ "Python","Java", "Machine Learning", "Data Science"],
        "contact":[
            { phone: { type: "cell", number: "923042516485" }},
            { mail: { type: "official", email: "mehvishofficial@gmail.com"}}
        ]
    },
    {
        "name": {first: "Aftab", last: "Raza"},
        "age": 25,
        "gender": "Male",
        "discipline": "BSIT",
        "joining_year": 2012,
        "department": "Information Technology",
        "courses":[ "Python","JavaScript", "Information Security"],
        "contact":[
            { phone: { type: "landline", number: "111-444-5555" }},
            { mail: { type: "personal", email: "aftab@hotmail.com"}}
        ]
    }
])

db.students.find().pretty()

Output:

{
        "_id" : ObjectId("6298ef54271c5124b739d7d3"),
        "name" : {
                "first" : "Mehvish",
                "last" : "Ashiq"
        },
        "age" : 30,
        "gender" : "Female",
        "discipline" : "BSCS",
        "joining_year" : 2014,
        "department" : "Computer Science",
        "courses" : [
                "Python",
                "Java",
                "Machine Learning",
                "Data Science"
        ],
        "contact" : [
                {
                        "phone" : {
                                "type" : "cell",
                                "number" : "923042516485"
                        }
                },
                {
                        "mail" : {
                                "type" : "official",
                                "email" : "mehvishofficial@gmail.com"
                        }
                }
        ]
}
{
        "_id" : ObjectId("6298ef54271c5124b739d7d4"),
        "name" : {
                "first" : "Aftab",
                "last" : "Raza"
        },
        "age" : 25,
        "gender" : "Male",
        "discipline" : "BSIT",
        "joining_year" : 2012,
        "department" : "Information Technology",
        "courses" : [
                "Python",
                "JavaScript",
                "Information Security"
        ],
        "contact" : [
                {
                        "phone" : {
                                "type" : "landline",
                                "number" : "111-444-5555"
                        }
                },
                {
                        "mail" : {
                                "type" : "personal",
                                "email" : "aftab@hotmail.com"
                        }
                }
        ]
}

The only reason to have a bit complicated documents is to learn the use of the $nin comparison operator with different fields. For instance, a single field, a field with the embedded document, a field containing an array, and an array of embedded documents.

Use the $nin Operator With the find() Method to Query a Field in MongoDB

Example Code:

db.students.find({ "joining_year": { $nin: [2011,2014] }}).pretty();

Output:

{
        "_id" : ObjectId("6298ef54271c5124b739d7d4"),
        "name" : {
                "first" : "Aftab",
                "last" : "Raza"
        },
        "age" : 25,
        "gender" : "Male",
        "discipline" : "BSIT",
        "joining_year" : 2012,
        "department" : "Information Technology",
        "courses" : [
                "Python",
                "JavaScript",
                "Information Security"
        ],
        "contact" : [
                {
                        "phone" : {
                                "type" : "landline",
                                "number" : "111-444-5555"
                        }
                },
                {
                        "mail" : {
                                "type" : "personal",
                                "email" : "aftab@hotmail.com"
                        }
                }
        ]
}

In this example, we use the $nin operator with the find() method to search for the whole documents where the joining_year is neither 2011 nor 2014.

We can use the command in the following manner if we want to have certain fields only instead of the whole document. Write 1 to print the field and its value on the computer screen, while 0 means we don’t want this field in the result set.

Example Code:

db.students.find(
    { "joining_year": { $nin: [2011,2014] }},
    {"name": 1, "discipline": 1, "department": 1, "_id":0}
).pretty();

Output:

{
        "name" : {
                "first" : "Aftab",
                "last" : "Raza"
        },
        "discipline" : "BSIT",
        "department" : "Information Technology"
}

Use the $nin Operator With the find() Method to Query an Embedded Document in MongoDB

Example Code:

db.students.find(
    { "name.last": { $nin: ["Raza", "Ali"] }},
    { "name": 1, "gender": 1, "age": 1, "_id":0}
).pretty();

Output:

{
        "name" : {
                "first" : "Mehvish",
                "last" : "Ashiq"
        },
        "age" : 30,
        "gender" : "Female"
}

The sample documents have a field named name for this tutorial, which further contains the embedded document with two fields (first and last). To use the $nin comparison operator with the name field, we use the dot notation name.first.

For this code snippet, we are trying to retrieve the name, age, and gender for those documents where the value of the name.last is not the member of the specified array for the $nin operator.

We get the specified fields from those documents where the name.last is neither Raza nor Ali. We can also use the AND condition with the $nin operator.

Example Code:

db.students.find(
    { "name.last": { $nin: ["Raza", "Ali"]}, "name.first": {$nin: ["Mehvish"]}},
    { "name": 1, "gender": 1, "age": 1, "_id":0}
).pretty();

This time, we will not get any output because we have two documents where the first document has Mehvish as the value of name.first while the second document contains the Raza as the value of name.last field. So, both documents are excluded from the result set, and we got nothing.

Use the $nin Operator With the find() Method to Query an Array in MongoDB

Example Code:

db.students.find(
    { "courses": { $nin: ["JavaScript", "Networking", "Psychology"] }},
    { "courses": 1, "department": 1, "_id":0}
).pretty();

Output:

{
        "department" : "Computer Science",
        "courses" : [
                "Python",
                "Java",
                "Machine Learning",
                "Data Science"
        ]
}

Understand this output carefully. In this output, the course field holds an array with no element equal to the value in the given array for the $nin operator.

The whole document where any field containing an array with elements equal to the JavaScript, Networking, or Psychology will be excluded from the result set.

Use the $nin Operator With the find() Method to Query an Array of Documents in MongoDB

Carefully observe the contact field we used while populating the students collection at the beginning of this tutorial. It contains an array of documents where each document has an embedded (nested) document.

How to query that using the $nin operator? See the example given below.

db.students.find(
    { "contact.phone.type": { $nin: ["cell"] }},
    { "contact": 1, "department": 1, "_id":0}
).pretty();

Output:

{
        "department" : "Information Technology",
        "contact" : [
                {
                        "phone" : {
                                "type" : "landline",
                                "number" : "111-444-5555"
                        }
                },
                {
                        "mail" : {
                                "type" : "personal",
                                "email" : "aftab@hotmail.com"
                        }
                }
        ]
}

Use the $nin Comparison Operator With the update() Method to Update a Field Value in MongoDB

Example Code:

db.students.update(
    { "joining_year": {$nin: [2011,2014]}},
    { $set: {"joining_year": 2000}}
);

In this code snippet, we retrieve the documents where the joining_year is neither 2014 nor 2011 and then set the value of the joining_year to 2000. Next, use the following command to see the updated document.

db.students.find().pretty()

Use the $nin Operator With Regular Expressions in MongoDB

Example Code:

var array_of_regex = [/Data+/];
db.students.find(
    { "courses": {$nin: array_of_regex}},
    {"name":1, "courses":1, "department":1, "_id":0}
).pretty();

Output:

{
        "name" : {
                "first" : "Aftab",
                "last" : "Raza"
        },
        "department" : "Information Technology",
        "courses" : [
                "Python",
                "JavaScript",
                "Information Security"
        ]
}

For this example, we make an array that can contain different regular expressions. For now, we have only one regular expression.

Why do we have to make an array of regexes? It is because the $nin takes an array to compare with.

Mehvish Ashiq avatar Mehvish Ashiq avatar

Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.

LinkedIn GitHub Facebook

Related Article - MongoDB Operator