$nin

On this page本页内容

$nin

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

$nin selects the documents where:选择文档,其中:

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比较顺序

Examples示例

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" ] }
] )

Select on Unmatching Documents选择不匹配的文档

The following query selects all documents from the inventory collection where the quantity does not equal either 5 or 15.以下查询从inventory集合中选择quantity不等于515的所有文档。

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' ] }

Select on Elements Not in an Array选择不在数组中的元素

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.另请参见查询选择性

Tip提示
See also: 参阅:
←  $neLogical Query Operators →