

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# \$1nin
<a name="nin"></a>

该`$nin`运算符用于匹配不在指定数组中的值。它是`$in`运算符的倒数，它匹配指定数组中的值。

Planner 版本 2.0 添加了对索引的支持`$nin`。

**参数**
+ `field`：要检查的字段。
+ `array`：要检查的值数组。

 

**字段名称中的美元 (`$`)**

有关在嵌套对象中查询`$`前缀字段的限制`$nin`，请参阅[字段名称中的美元符号（\$1）和句点（.）](functional-differences.md#functional-differences-dollardot)。

## 示例（MongoDB 外壳）
<a name="nin-examples"></a>

以下示例演示如何使用`$nin`运算符来查找`category`字段不等于 “虚构” 或 “神秘” 的文档。

**创建示例文档**

```
db.books.insertMany([
  { title: "The Great Gatsby", author: "F. Scott Fitzgerald", category: "Fiction" },
  { title: "To Kill a Mockingbird", author: "Harper Lee", category: "Fiction" },
  { title: "The Girl on the Train", author: "Paula Hawkins", category: "Mystery" },
  { title: "The Martian", author: "Andy Weir", category: "Science Fiction" },
  { title: "The Alchemist", author: "Paulo Coelho", category: "Philosophy" }
])
```

**查询示例**

```
db.books.find({
  category: {
    $nin: ["Fiction", "Mystery"]
  }
})
```

**输出**

```
[
  {
    _id: ObjectId('...'),
    title: 'The Martian',
    author: 'Andy Weir',
    category: 'Science Fiction'
  },
  {
    _id: ObjectId('...'),
    title: 'The Alchemist',
    author: 'Paulo Coelho',
    category: 'Philosophy'
  }
]
```

## 代码示例
<a name="nin-code"></a>

要查看使用该`$nin`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findBooksNotInCategories(categories) {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const books = await db.collection('books').find({
    category: {
      $nin: categories
    }
  }).toArray();
  console.log(books);
  client.close();
}

findBooksNotInCategories(['Fiction', 'Mystery']);
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_books_not_in_categories(categories):
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    books = list(db.books.find({
        'category': {
            '$nin': categories
        }
    }))
    print(books)
    client.close()

find_books_not_in_categories(['Fiction', 'Mystery'])
```

------