$max - Amazon DocumentDB

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

$max

$max 集約ステージは、パイプラインステージ内のすべてのドキュメントで指定されたフィールドの最大値を返すために使用されます。この演算子は、一連のドキュメントで最大値を見つけるのに役立ちます。

パラメータ

  • expression: 最大値の計算に使用する式。

例 (MongoDB シェル)

次の例は、 $max演算子を使用して学生ドキュメントのコレクションで最大スコアを検索する方法を示しています。$group ステージはすべてのドキュメントをグループ化し、 $max演算子を使用してすべてのドキュメントの scoreフィールドの最大値を計算します。

サンプルドキュメントを作成する

db.students.insertMany([ { name: "John", score: 85 }, { name: "Jane", score: 92 }, { name: "Bob", score: 78 }, { name: "Alice", score: 90 } ])

クエリの例

db.students.aggregate([ { $group: { _id: null, maxScore: { $max: "$score" } } }, { $project: { _id: 0, maxScore: 1 } } ])

出力

[ { maxScore: 92 } ]

コードの例

$max コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

Node.js
const { MongoClient } = require('mongodb'); async function findMaxScore() { 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 students = db.collection('students'); const result = await students.aggregate([ { $group: { _id: null, maxScore: { $max: "$score" } } } ]).toArray(); console.log(result); await client.close(); } findMaxScore();
Python
from pymongo import MongoClient def find_max_score(): client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false') db = client['test'] students = db.students result = list(students.aggregate([ { "$group": { "_id": None, "maxScore": { "$max": "$score" } } } ])) print(result) client.close() find_max_score()