MongoDB $nin Operator

What is the $nin operator in MongoDB?

MongoDB provides a variety of comparison query operators. The $nin (not in) operator is one of those operators. The $nin operator is used to select documents where the value of a field is not equal to any of the given values in the array.

Syntax of the $nin operator:

Examples:

Suppose we have a collection of the products with the following documents.

Example 1: Using $nin Operator

In this example, we are retrieving only those products documents that do not have a specific _id (4, 5, and 6) value.

Output:

{ 
   "_id" : 1, 
   "product_name" : "Shirt", 
   "sizes" : [ "S", "M", "XL", "XXL" ] 
}
{  
   "_id" : 2, 
   "product_name" : "T-Shirt", 
   "sizes" : [ "S", "L", "XL" ] 
}
{ 
   "_id" : 3, 
   "product_name" : "Shorts", 
   "sizes" : [ "XS", "S", "M", "L", "XL" ] 
}

Example 2: Another Field

In this example, we're going to use the $nin operator against a different field.

Output:

{  
   "_id" : 2, 
   "product_name" : "T-Shirt", 
   "sizes" : [ "S", "L", "XL" ] 
}
{ 
   "_id" : 3, 
   "product_name" : "Shorts", 
   "sizes" : [ "XS", "S", "M", "L", "XL" ] 
}
{ 
   "_id" : 4, 
   "product_name" : "Jeans", 
   "sizes" : "L" 
}
{ 
   "_id" : 5, 
   "product_name" : "CottonShirts", 
   "sizes" : null 
}
{ 
   "_id" : 6, 
   "product_name" : "CottonShorts" 
}

Example 3: Using the $nin operator with regular expressions

Output:

{ 
   "_id" : 4, 
   "product_name" : "Jeans", 
   "sizes" : "L" 
}
{ 
   "_id" : 5, 
   "product_name" : "CottonShirts", 
   "sizes" : null 
}
{ 
   "_id" : 6, 
   "product_name" : "CottonShorts" 
}

Example 4: Update data using $nin operator

In this example, we are using the update() method with the $nin and $set operators to update the "sizes" field in documents whose product_name is not Shirt, T-Shirt, Shorts, Jeans, or CottonShorts.

Output:

{ 
   "_id" : 5, 
   "product_name" : "CottonShirts", 
   "sizes" : 40 
}





Latest Courses