Introduction to MongoDB $nin Operator

The $nin operator in MongoDB is used to find documents in the MongoDB database that do not match a specified condition. It is an operator in the MongoDB query language that can be combined with other operators to build more complex query statements.

Syntax

The syntax for the $nin operator is as follows:

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

Here, <field> is the field to be queried, and <value1>, <value2> etc. are values that do not meet the query conditions.

Use Cases

The $nin operator is commonly used to filter documents that do not meet specific conditions, for example:

  1. Querying products in a collection that do not belong to a specific category.
  2. Querying users in a collection that are not in a specific list.
  3. Querying orders in a collection that do not belong to a certain time period.

Example

Suppose we have a collection named users that stores information about users’ names and ages. We want to query users who are not in a specific age range, and we can use the $nin operator to achieve this:

db.users.find({ age: { $nin: [18, 20, 22] } })

The above query statement will return information about all users whose age is not 18, 20, or 22.

Suppose the following documents exist in the collection:

{ "name": "Alice", "age": 18 }
{ "name": "Bob", "age": 20 }
{ "name": "Charlie", "age": 22 }
{ "name": "David", "age": 24 }
{ "name": "Eve", "age": 26 }

Then executing the following query statement:

db.users.find({ age: { $nin: [18, 20, 22] } })

Will return the following results:

{ "name": "David", "age": 24 }
{ "name": "Eve", "age": 26 }

Conclusion

The $nin operator is a commonly used operator in the MongoDB query language, which can be used to filter documents that do not meet specified conditions. It can be combined with other operators to build more complex query statements.