$nin$ninselects 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不等于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' ] }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.另请参见创建选择性查询。