

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

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

`$not` 運算子用於否定指定表達式的結果。它可讓您選取指定條件不相符的文件。

規劃器 2.0 版新增了 `$not {eq}`和 的索引支援。 `$not {in}`

**參數**
+ `expression`：要否定的表達式。

## 範例 (MongoDB Shell)
<a name="not-examples"></a>

下列範例示範如何使用 `$not`運算子來尋找`status`欄位不等於「作用中」的文件。

**建立範例文件**

```
db.users.insertMany([
  { name: "John", status: "active" },
  { name: "Jane", status: "inactive" },
  { name: "Bob", status: "pending" },
  { name: "Alice", status: "active" }
]);
```

**查詢範例**

```
db.users.find({ status: { $not: { $eq: "active" } } });
```

**輸出**

```
[
  {
    _id: ObjectId('...'),
    name: 'Jane',
    status: 'inactive'
  },
  {
    _id: ObjectId('...'),
    name: 'Bob',
    status: 'pending'
  }
]
```

## 程式碼範例
<a name="not-code"></a>

若要檢視使用 `$not`命令的程式碼範例，請選擇您要使用的語言標籤：

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

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

async function main() {
  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 collection = db.collection('users');

  const result = await collection.find({
    status: { $not: { $eq: "active" } }
  }).toArray();

  console.log(result);

  await client.close();
}

main();
```

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

```
from pymongo import MongoClient
from bson.son import SON

client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
collection = db['users']

result = collection.find({
    "status": {"$not": {"$eq": "active"}}
})

for doc in result:
    print(doc)

client.close()
```

------