

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

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

Amazon DocumentDB の `$cmp`演算子は、2 つの値を比較し、相対的な順序を示す整数値を返すために使用されます。これは、2 つの式を比較し、最初の値がそれぞれ 2 番目の値より小さい、等しい、または大きいかどうかに応じて、-1、0、または 1 の整数値を返す比較演算子です。

**パラメータ**
+ `expression1`: 比較する最初の式。
+ `expression2`: 比較する 2 番目の式。

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

次の例は、`$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).
```

## コードの例
<a name="cmp-code"></a>

`$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 }
]
```

------