翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
$cmp
Amazon DocumentDB の $cmp演算子は、2 つの値を比較し、相対的な順序を示す整数値を返すために使用されます。これは、2 つの式を比較し、最初の値がそれぞれ 2 番目の値より小さい、等しい、または大きいかどうかに応じて、-1、0、または 1 の整数値を返す比較演算子です。
パラメータ
例 (MongoDB シェル)
次の例は、$cmp演算子を使用して 2 つの数値を比較する方法を示しています。
サンプルドキュメントを作成する
db.collection.insertMany([
{ _id: 1, value1: 10, value2: 20 },
{ _id: 2, value1: 15, value2: 15 },
{ _id: 3, value1: 20, value2: 10 }
]);
クエリの例
db.collection.find({
$expr: {
$cmp: ["$value1", "$value2"]
}
})
出力
[
{ "_id" : 1, "value1" : 10, "value2" : 20 },
{ "_id" : 3, "value1" : 20, "value2" : 10 }
]
この例では、 $cmp演算子は各ドキュメントの フィールドvalue1と value2フィールドを比較します。結果は、次のとおりです。
- `$cmp: ["$value1", "$value2"]` returns -1 for the first document (10 < 20), 0 for the second document (15 = 15), and 1 for the third document (20 > 10).
コードの例
$cmp コマンドを使用するためのコード例を表示するには、使用する言語のタブを選択します。
- Node.js
-
mongodb ドライバーで Node.js アプリケーションで $cmp演算子を使用する例を次に示します。
const { MongoClient } = require('mongodb');
const client = new MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
async function main() {
await client.connect();
const db = client.db('test');
const collection = db.collection('mycollection');
// Insert sample documents
await collection.insertMany([
{ _id: 1, value1: 10, value2: 20 },
{ _id: 2, value1: 15, value2: 15 },
{ _id: 3, value1: 20, value2: 10 }
]);
// Query using $cmp operator
const result = await collection.find({
$expr: {
$cmp: ['$value1', '$value2']
}
}).toArray();
console.log(result);
await client.close();
}
main();
- Python
-
pymongo ドライバーで Python アプリケーションで $cmp演算子を使用する例を次に示します。
from pymongo import MongoClient
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['mycollection']
# Insert sample documents
collection.insert_many([
{'_id': 1, 'value1': 10, 'value2': 20},
{'_id': 2, 'value1': 15, 'value2': 15},
{'_id': 3, 'value1': 20, 'value2': 10}
])
# Query using $cmp operator
result = list(collection.find({
'$expr': {
'$cmp': ['$value1', '$value2']
}
}))
print(result)
client.close()
Node.js と Python の両方の例の出力は、MongoDB シェルの例と同じになります。
[
{ "_id" : 1, "value1" : 10, "value2" : 20 },
{ "_id" : 2, "value1" : 15, "value2" : 15 },
{ "_id" : 3, "value1" : 20, "value2" : 10 }
]