

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

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

`$nin` 演算子は、指定された配列にない値を一致させるために使用されます。これは、指定された配列の値と一致する `$in`演算子の逆です。

プランナーバージョン 2.0 で のインデックスサポートが追加されました`$nin`。

**パラメータ**
+ `field`: 確認するフィールド。
+ `array`: チェックする値の配列。

 

**フィールド名のドル (`$`)**

ネストされたオブジェクトの `$nin`の`$`プレフィックス付きフィールドのクエリに関する制限[フィールド名のドル (\$1) とドット (.)](functional-differences.md#functional-differences-dollardot)については、「」を参照してください。

## 例 (MongoDB シェル)
<a name="nin-examples"></a>

次の例は、 `$nin`演算子を使用して、 `category`フィールドが「Fiction」または「Mystery」と等しくないドキュメントを検索する方法を示しています。

**サンプルドキュメントを作成する**

```
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'])
```

------