本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$max
只有在指定的值大於目前的欄位值時,$max更新運算子才會更新欄位的值。此運算子有助於跨更新維持最大值。
參數
-
field:要更新的欄位。
-
value:要與目前欄位值比較的值。
範例 (MongoDB Shell)
下列範例示範如何使用 $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 }
程式碼範例
若要檢視使用 $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()