翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
$max
$max 更新演算子は、指定された値が現在のフィールド値より大きい場合にのみ、フィールドの値を更新します。この演算子は、更新全体で最大値を維持するのに役立ちます。
パラメータ
-
field: 更新するフィールド。
-
value: 現在のフィールド値と比較する値。
例 (MongoDB シェル)
次の例は、 $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 が現在の値である 85 より大きいため、95 に更新されます。
{ "_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()