

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

# \$1max
<a name="max-update"></a>

只有当指定值大于当前字段值时，`$max`更新运算符才会更新字段的值。此运算符对于在更新期间保持最大值很有用。

**参数**
+ `field`：要更新的字段。
+ `value`：要与当前字段值进行比较的值。

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

以下示例演示如何使用`$max`运算符更新玩家记录的最高分数。

**创建示例文档**

```
db.scores.insertMany([
  { _id: 1, player: "Alice", highScore: 85 },
  { _id: 2, player: "Bob", highScore: 92 },
  { _id: 3, player: "Charlie", highScore: 78 }
])
```

**更新示例**

```
db.scores.updateOne(
  { _id: 1 },
  { $max: { highScore: 95 } }
)
```

**结果**

Alice 的`highScore`字段更新为 95，因为 95 大于当前值 85。

```
{ "_id": 1, "player": "Alice", "highScore": 95 }
```

## 代码示例
<a name="max-update-code"></a>

要查看使用该`$max`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ 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('scores');

  const result = await collection.updateOne(
    { _id: 1 },
    { $max: { highScore: 95 } }
  );

  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['scores']

    result = collection.update_one(
        { '_id': 1 },
        { '$max': { 'highScore': 95 } }
    )

    print(result)
    client.close()

example()
```

------