Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /

$nin (query predicate operator)

$nin

$nin selects documents where:

  • the specified field value is not in the specified array or

  • the specified field does not exist.

You can use $nin for deployments hosted in the following environments:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud

  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB

  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB

The $nin operator has the following form:

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

If field has an array, the $nin operator selects the documents whose field has an array with no element equal to a value in the specified array. For example, <value1>, <value2>, and so on.

For comparison of different BSON type values, see the specified BSON comparison order.

The examples on this page use data from the sample_mflix sample dataset. For details on how to load this dataset into your self-managed MongoDB deployment, see Load the sample dataset. If you made any modifications to the sample databases, you may need to drop and recreate the databases to run the examples on this page.

The following example returns movies where runtime is greater than 1000 minutes and rated is not in [ "G", "PG" ]. Because $nin also matches documents that don't contain the rated field, the query returns movies even when the rating data is unavailable:

db.movies.find(
{ rated: { $nin: [ "G", "PG" ] }, runtime: { $gt: 1000 } },
{ _id: 0, title: 1, year: 1, rated: 1 }
)
[
{ title: 'Centennial', year: 1978 },
{
title: 'Baseball',
year: 1994,
rated: 'TV-PG'
}
]

The following example sets the exclude field to true for movies that don't have "Drama" in their genres array:

db.movies.updateMany(
{ genres: { $nin: [ "Drama" ] } },
{ $set: { exclude: true } }
)
{
acknowledged: true,
insertedId: null,
matchedCount: ...,
modifiedCount: ...,
upsertedCount: 0
}

updateMany() also selects a document when the document does not contain the field $nin is matching on.

The inequality operator $nin is not very selective since it often matches a large portion of the index. As a result, in many cases, a $nin query with an index may perform no better than a $nin query that must scan all documents in a collection. See also Create Selective Queries.

Back

$ne

On this page