On this page本页内容
Syntax: 语法:{ field: { $nin: [ <value1>, <value2> ... <valueN> ] } }
$nin
selects the documents where:选择文档,其中:
field
value is not in the specified array
orfield
值不在指定的array
中,或field
does not exist.field
不存在。If the 如果field
holds an array, then the $nin
operator selects the documents whose field
holds an array with no element equal to a value in the specified array (for example, <value1>
, <value2>
, and so on).field
包含数组,则$nin
运算符选择其字段包含数组的文档,该数组的元素不等于指定数组中的值(例如,<value1>
、<value2>
等)。
For comparison of different BSON type values, see the specified BSON comparison order.有关不同BSON类型值的比较,请参阅指定的BSON比较顺序。
Create the 创建inventory
collection:inventory
集合:
db.inventory.insertMany( [ { "item": "Pens", "quantity": 350, "tags": [ "school", "office" ] }, { "item": "Erasers", "quantity": 15, "tags": [ "school", "home" ] }, { "item": "Maps", "tags": [ "office", "storage" ] }, { "item": "Books", "quantity": 5, "tags": [ "school", "storage", "home" ] } ] )
The following query selects all documents from the 以下查询从inventory
collection where the quantity
does not equal either 5 or 15.inventory
集合中选择quantity
不等于5
或15
的所有文档。
The query also matches documents that do not have a 该查询还匹配没有quantity
field.quantity
字段的文档。
db.inventory.find( { quantity: { $nin: [ 5, 15 ] } }, { _id: 0 } )
Example output:示例输出:
{ item: 'Pens', quantity: 350, tags: [ 'school', 'office' ] }, { item: 'Maps', tags: [ 'office', 'storage' ] }
Set the 对于没有exclude
field to true
for documents that don't have the "school"
tag."school"
标记的文档,将exclude
字段设置为true
。
db.inventory.updateMany( { tags: { $nin: [ "school" ] } }, { $set: { exclude: true } } )
当文档不包含updateMany()
also selects a document when the document does not contain the field $nin
is matching on.$nin
匹配的字段时,updateMany()
也会选择一个文档。
The inequality operator 不等式运算符$nin
is not very selective since it often matches a large portion of the index. $nin
不是很有选择性,因为它通常与索引的很大一部分相匹配。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. $nin
查询的性能可能并不比必须扫描集合中所有文档的$nim
查询好。See also Query Selectivity.另请参见查询选择性。