Database Manual / Reference / Query Language / Query Predicates / Comparison

$nin

$nin

$nin selects the documents where:选择以下文档:

  • the specified field value is not in the specified array or指定的字段值不在指定的数组中,或者
  • the specified field does not exist.指定的字段不存在。

Compatibility兼容性

You can use $nin for deployments hosted in the following environments:您可以将$nin用于在以下环境中托管的部署:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务
  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本

Syntax语法

The $nin operator has the following form:$nin运算符具有以下形式:

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

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匹配的字段时,也会选择文档。

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查询的性能可能并不比必须扫描集合中所有文档的$nin搜索好。See also Create Selective Queries.另请参见创建选择性查询