$ne - Amazon DocumentDB

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

$ne

$ne 彙總運算子會比較兩個值,並在它們不相等true時傳回 ,否則傳回 false

參數

  • expression1:要比較的第一個值。

  • expression2:要比較的第二個值。

範例 (MongoDB Shell)

下列範例示範如何使用 $ne 運算子來識別具有狀態變更的訂單。

建立範例文件

db.orders.insertMany([ { _id: 1, orderId: "A123", status: "shipped", expectedStatus: "shipped" }, { _id: 2, orderId: "B456", status: "pending", expectedStatus: "shipped" }, { _id: 3, orderId: "C789", status: "delivered", expectedStatus: "delivered" } ]);

查詢範例

db.orders.aggregate([ { $project: { orderId: 1, status: 1, expectedStatus: 1, needsAttention: { $ne: ["$status", "$expectedStatus"] } } } ]);

輸出

[ { _id: 1, orderId: 'A123', status: 'shipped', expectedStatus: 'shipped', needsAttention: false }, { _id: 2, orderId: 'B456', status: 'pending', expectedStatus: 'shipped', needsAttention: true }, { _id: 3, orderId: 'C789', status: 'delivered', expectedStatus: 'delivered', needsAttention: false } ]

程式碼範例

若要檢視使用$ne彙總運算子的程式碼範例,請選擇您要使用的語言標籤:

Node.js
const { MongoClient } = require('mongodb'); async function example() { 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('orders'); const result = await collection.aggregate([ { $project: { orderId: 1, status: 1, expectedStatus: 1, needsAttention: { $ne: ["$status", "$expectedStatus"] } } } ]).toArray(); console.log(result); await client.close(); } example();
Python
from pymongo import MongoClient def example(): 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['orders'] result = list(collection.aggregate([ { '$project': { 'orderId': 1, 'status': 1, 'expectedStatus': 1, 'needsAttention': { '$ne': ['$status', '$expectedStatus'] } } } ])) print(result) client.close() example()