本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$not
$not 運算子用於否定指定表達式的結果。它可讓您選取指定條件不相符的文件。
規劃器 2.0 版新增了 $not {eq}和 的索引支援。 $not {in}
參數
範例 (MongoDB Shell)
下列範例示範如何使用 $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'
}
]
程式碼範例
若要檢視使用 $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()