Docs Menu

Docs HomeDevelop ApplicationsMongoDB Manual

$nin

On this page

  • Compatibility
  • Syntax
$nin

$nin selects the 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

The $nin operator has the following form:

{ field: { $nin: [ <value1>, <value2> ... <valueN> ] } }
.. include:: /includes/fact-comparison-order.rst
Consider the following query:
.. code-block:: javascript
db.inventory.find( { qty: { $nin: [ 5, 15 ] } } )
This query will select all documents in the ``inventory`` collection
where the ``qty`` field value does **not** equal ``5`` nor
``15``. The selected documents will include those documents that do
*not* contain the ``qty`` field.
If the ``field`` holds an array, then the :query:`$nin` operator
selects the documents whose ``field`` holds an array with **no**
element equal to a value in the specified array (e.g. ``<value1>``,
``<value2>``, etc.).
Consider the following query:
.. code-block:: javascript
db.inventory.update( { tags: { $nin: [ "appliances", "school" ] } }, { $set: { sale: false } } )
This :method:`~db.collection.update()` operation will set
the ``sale`` field value in the ``inventory`` collection where the
``tags`` field holds an array with **no** elements matching an
element in the array ``["appliances", "school"]`` or where a
document does not contain the ``tags`` field.
.. include:: /includes/extracts/nin_operators_selectivity.rst
.. seealso::
- :method:`~db.collection.find()`
- :method:`~db.collection.update()`
- :update:`$set`
← $ne