

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

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

Amazon DocumentDB 中的`$cmp`运算符用于比较两个值并返回一个表示其相对顺序的整数值。它是一个比较运算符，它比较两个表达式并分别返回 -1、0 或 1 的整数值，具体取决于第一个值是小于、等于还是大于第二个值。

**参数**
+ `expression1`：第一个要比较的表达式。
+ `expression2`：第二个要比较的表达式。

## 示例（MongoDB 外壳）
<a name="cmp-examples"></a>

以下示例演示如何使用运`$cmp`算符比较两个数值。

**创建示例文档**

```
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 Shell 示例的输出相同：

```
[
  { "_id" : 1, "value1" : 10, "value2" : 20 },
  { "_id" : 2, "value1" : 15, "value2" : 15 },
  { "_id" : 3, "value1" : 20, "value2" : 10 }
]
```

------