Open In App

MongoDB – $nin Operator

Improve
Improve
Like Article
Like
Save
Share
Report

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.
If the field contain an array, then this operator selects only those documents whose field contains an array that holds no item that matches a value of the specified array. You can use this operator in methods like find(), update(), etc. according to your requirements.

Syntax:

{field: {$nin: [value1, value2, value3, ...]}}

In the following examples, we are working with:

Database: GeeksforGeeks
Collection: contributor
Document: three documents that contain the details of the contributors in the form of field-value pairs.

Matching values using $nin operator:

In this example, we are retrieving only those employee’s documents whose name is not Amit or Suman.




db.contributor.find({name: {$nin: ["Amit", "Suman"]}}).pretty()


Matching values in an array using $nin operator:

In this example, we are retrieving only those employee’s documents who is not working with either C#, Python, or both languages.




db.contributor.find({language: {$nin: ["C#", "Python"]}}).pretty()


Matching values in embedded/nested documents using $nin operator:

In this example, we are retrieving only those employee’s documents whose age is not 25 or 22.




db.contributor.find({"personal.age": { $nin: [25, 22]}}).pretty()


Updating data using $nin operator:

In this example, we are adding a new field-value pair(i.e, salary: 10000) in the documents of those employee’s whose name is not Amit or Priya by using update() method with $in and $set operators.




db.contributor.update({name: {$nin: ["Amit", "Priya"]}},
                             {$set: {salary: 1000}})


Note: The update() method by default update only one document at a time. If you want to update multiple documents, then set the value of its multi parameter to true. So, in this example, the update() method updated the first document that matches the given condition as shown in the below image.



Last Updated : 22 Apr, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads