$nin
On this page本页内容
$nin
Syntax: { field: { $nin: [ <value1>, <value2> ... <valueN> ] } }
$nin selects the documents where:选择以下文档:
thefieldvalue is not in the specifiedarrayorfield值不在指定的array中,或者the该fielddoes 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).$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 Query Selectivity.另请参见查询选择性。