View a markdown version of this page

$top - Amazon DocumentDB

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

$top

バージョン 8.0.1 から新規。

$group ステージで $top アキュムレータを使用して、指定されたソート順序に従ってグループごとに最高ランクのドキュメントを返します。

パラメータ

  • sortBy: ソート順序を指定するドキュメント。昇順1の場合は 、降順-1の場合は を使用します。

  • output: 上部のドキュメントから返すフィールドを指定する式。

例 (MongoDB シェル)

次の例は、 $top アキュムレータを使用して、売上コレクション内のアイテムあたりの上位売上 (最大数量) を検索する方法を示しています。

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

db.sales.insertMany([ { item: "abc", quantity: 10, price: 5 }, { item: "abc", quantity: 5, price: 8 }, { item: "xyz", quantity: 15, price: 3 }, { item: "xyz", quantity: 7, price: 6 } ])

クエリの例

db.sales.aggregate([ { $group: { _id: "$item", topSale: { $top: { sortBy: { quantity: -1 }, output: { quantity: "$quantity", price: "$price" } } } } } ])

出力

[ { "_id": "xyz", "topSale": { "quantity": 15, "price": 3 } }, { "_id": "abc", "topSale": { "quantity": 10, "price": 5 } } ]

コードの例

$top 演算子を使用するコード例を表示するには、使用する言語のタブを選択します。

Node.js
const { MongoClient } = require('mongodb'); async function example() { const uri = 'mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'; const client = new MongoClient(uri); try { await client.connect(); const db = client.db('test'); const collection = db.collection('sales'); const result = await collection.aggregate([ { $group: { _id: "$item", topSale: { $top: { sortBy: { quantity: -1 }, output: { quantity: "$quantity", price: "$price" } } } } } ]).toArray(); console.log(result); } catch (error) { console.error('Error:', error); } finally { await client.close(); } } example();
Python
from pymongo import MongoClient from pprint import pprint def example(): client = None try: 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['sales'] result = list(collection.aggregate([ { '$group': { '_id': '$item', 'topSale': { '$top': { 'sortBy': { 'quantity': -1 }, 'output': { 'quantity': '$quantity', 'price': '$price' } } } } } ])) pprint(result) except Exception as e: print(f"An error occurred: {e}") finally: if client: client.close() example()