mongo-db
  1. mongo-db-nin-operator

$nin Operator - (MongoDB Misc)

In MongoDB, $nin operator is used to select documents where the value of a field is not equal to any value in the specified array or values. This page explains the syntax, example usage, output, explanation, use cases, important points, and summary of the $nin operator in MongoDB.

Syntax

The following is the syntax of the $nin operator:

{ field: { $nin: [<value1>, <value2>, ... <valueN> ] } }

Here, the field specifies the name of the field against which the $nin operator is used, and <value1>, <value2>, ... <valueN> denotes an array of values used for comparison. MongoDB checks this array to see if any of the values are not equal to the field.

Example

Consider a collection students with the following documents:

{ "_id": 1, "name": "Alice", "age": 25 }
{ "_id": 2, "name": "Bob", "age": 30 }
{ "_id": 3, "name": "Charlie", "age": 22 }
{ "_id": 4, "name": "David", "age": 26 }

To find all documents where the age field is not equal to 25 or 26, you can use the following query:

db.students.find( { age: { $nin: [25,26] } } )

This query returns the following documents:

{ "_id": 2, "name": "Bob", "age": 30 }
{ "_id": 3, "name": "Charlie", "age": 22 }

Output

The output of the $nin operator is the result set of documents matching the query filter.

Explanation

The $nin operator is used to select documents where the compared field does not match any of the specified values in an array.

Use cases

The $nin operator can be used in various scenarios, such as:

  • To select documents where a field value is not equal to a specific value.
  • To filter data based on multiple values.

Important Points

  • The $nin operator checks if any of the values in the specified array are not equal to the field value.
  • The $nin operator can be used to filter data based on multiple values.
  • The $nin operator is case-sensitive.

Summary

This page explained the syntax and usage of the $nin operator in MongoDB. We covered example usage, output, explanation, use cases, important points, and a summary of the operator. The $nin operator is useful for querying documents where a field does not match any of the specified values in an array.

Published on: