$nin
$nin
selects the documents where:
- the
field
value is not in the specifiedarray
or - the
field
does not exist.For comparison of different BSON type values, see the specifiedBSON comparison order.
Consider the following query:
- db.inventory.find( { qty: { $nin: [ 5, 15 ] } } )
This query will select all documents in the inventory
collectionwhere the qty
field value does not equal 5
nor15
. The selected documents will include those documents that donot contain the qty
field.
If the field
holds an array, then the $nin
operatorselects the documents whose field
holds an array with noelement equal to a value in the specified array (e.g. <value1>
,<value2>
, etc.).
Consider the following query:
- db.inventory.update( { tags: { $nin: [ "appliances", "school" ] } }, { $set: { sale: false } } )
This update()
operation will setthe sale
field value in the inventory
collection where thetags
field holds an array with no elements matching anelement in the array ["appliances", "school"]
or where adocument does not contain the tags
field.
The inequality operator $nin
is not very selective sinceit often matches a large portion of the index. As a result, in manycases, a $nin
query with an index may perform no betterthan a $nin
query that must scan all documents in acollection. See also Query Selectivity.
See also