NOT IN comparison operator in MongoDB
Comparison operators are very useful when working with large data sets. They are helpful in gaining insights from the data.
$nin
This article explains how to use the ( ) comparison operator
in MongoDB NOT IN
.
It also shows how to use $nin
with find()
and update()
methods in MongoDB. In addition, we will also learn about $nin
regular expressions using the operator.
$nin
( NOT IN
) comparison operator
in MongoDB
$nin
Is one of the comparison operators in MongoDB. This operator selects documents whose field value does not belong to the specified array, or the field does not exist.
If the field contains an array, array of documents, or array of embedded documents, then we will fetch only those documents where the field contains that array and no item is equal to the value in the given array (we will also see this case later in this tutorial).
Before we dive into more details, let's create a sample collection with some documents.
Sample 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 the document is a bit complex is to learn to use $nin
comparison operators with different fields. For example, a single field, a field containing an embedded document, a field containing an array, and an array of embedded documents.
$nin
Using the operator and find()
method to query fields
in MongoDB
Sample 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 $nin
the operator and find()
the method to search for the entire document joining_year
where is neither 2011
nor 2014
.
If we want to have only certain fields instead of the entire document, we can use the command as follows. Write 1
to print the field and its value on the computer screen, while 0
indicates that we do not want the field to appear in the result set.
Sample 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"
}
Querying Embedded Documents
in MongoDB Using $nin
the operator and methodfind()
Sample 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"
}
For this article, the sample document has a name
field called , which also contains an embedded document with two fields ( first
and ). To use the comparison operator with the field, we use dot notation .last
$nin
name
name.first
For this code snippet, we attempt to retrieve the , , and operators for documents whose name.last
value of is not $nin
a member of the specified array of .name
age
gender
We get the specified field
from those documents name.last
where is neither Raza
nor . We can also use the condition with the operator.Ali
AND
$nin
Sample 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 a value Mehvish
of as name.first
and the second document contains a value of Raza
as name.last
field. Therefore, both documents are excluded from the result set and we get nothing.
Querying arrays
in MongoDB using $nin
the operator and methodfind()
Sample 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, course
field contains an array where no element is equal to $nin
the value in the given array of the operator.
The entire document, any fields
containing arrays with elements equal to JavaScript
, , Networking
or will be excluded from the result set.Psychology
Querying an array of documents
in MongoDB using $nin
the operator and methodfind()
students
Take a close look at the field that we used when
populating the collection at the beginning of this tutorial contact
. It contains an array of documents, each of which has an embedded (nested) document.
How do I use $nin
the operator to query? 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 $nin
comparison operators and update()
methods to update field values in MongoDB
Sample code:
db.students.update(
{ "joining_year": {$nin: [2011,2014]}},
{ $set: {"joining_year": 2000}}
);
In this code snippet, we retrieve documents joining_year
where is neither 2014
nor and then set the value of to . Next, use the following command to view the updated document.2011
joining_year
2000
db.students.find().pretty()
$nin
Using the operator
with regular expressions in MongoDB
Sample 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 create an array that can contain different regular expressions. Currently, we only have one regular expression.
Why do we have to make an array of regular expressions? This is because $nin
we need an array to compare.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
List all collections in MongoDB Shell
Publish Date:2025/04/29 Views:156 Category:MongoDB
-
When using MongoDB , there are several ways to list the collections in the database. This article will discuss four different ways to get a list of collections in a MongoDB database. These methods are as follows: show collections List all c
Querying for non-null values in MongoDB
Publish Date:2025/04/29 Views:139 Category:MongoDB
-
This MongoDB article will explain how to query for non-null values in MongoDB. To query for non-null values, you can use $ne the operator and $eq the operator and then specify the desired value to query. This article shows the readers
Shutting down with code:100 error in MongoDB
Publish Date:2025/04/29 Views:53 Category:MongoDB
-
This MongoDB tutorial will teach you to fix the error on different operating systems shutting down with code:100 . It will also talk about the root cause of why this issue occurs. shutting down with code:100 Errors in MongoDB As we all know
SELECT COUNT GROUP BY in MongoDB
Publish Date:2025/04/29 Views:74 Category:MongoDB
-
In this article, we will discuss the functions in MongoDB. Also, we will point out the aggregation functions in detail. We will explain in detail the different ways to count and sort multiple and single fields of Group in MongoDB. Operation
Differences between MongoDB and Mongoose
Publish Date:2025/04/29 Views:80 Category:MongoDB
-
This MongoDB article will discuss the differences between MongoDB and Mongoose. Unfortunately, most beginners tend to confuse these two concepts when they start developing applications and use MongoDB as their backend. MongoDB has its own s
Install MongoDB using Homebrew
Publish Date:2025/04/29 Views:161 Category:MongoDB
-
MongoDB is a well-known unstructured database management system that can handle large amounts of data. It is a document-oriented database system and belongs to the NoSQL family (non-SQL). Data and records are stored as documents that look a
Create a MongoDB dump of the database
Publish Date:2025/04/29 Views:62 Category:MongoDB
-
In this MongoDB article, you’ll get a walkthrough of Mongodump and Mongorestore , how to use them, and some simple examples of backing up and restoring your collections using both tools. mongodump Commands in MongoDB Mongodump is a tool t
Get the size of the database in MongoDB
Publish Date:2025/04/29 Views:88 Category:MongoDB
-
When working in MongoDB, do you know the size of your database? Today, we will learn how to get the size of a database in MongoDB using show dbs the command and the method. db.stats() Get the size of the database in MongoDB We can show dbs;
Grouping values by multiple fields with MongoDB
Publish Date:2025/04/29 Views:99 Category:MongoDB
-
MongoDB Group by Multiple Fields is used to group values by multiple fields using various methods. One of the most efficient ways to group various fields present in MongoDB documents is by using $group the operator, which helps in per