View a markdown version of this page

$ 下部 - Amazon DocumentDB

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

$ 下部

バージョン 8.0.1 から新規。

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

パラメータ

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

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

例 (MongoDB シェル)

次の例は、 $bottom アキュムレータを使用して、売上コレクション内の項目あたりのボトムセール (最低数量) を検索する方法を示しています。

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

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", bottomSale: { $bottom: { sortBy: { quantity: -1 }, output: { quantity: "$quantity", price: "$price" } } } } } ])

出力

[ { "_id": "xyz", "bottomSale": { "quantity": 7, "price": 6 } }, { "_id": "abc", "bottomSale": { "quantity": 5, "price": 8 } } ]

コードの例

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

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", bottomSale: { $bottom: { 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', 'bottomSale': { '$bottom': { '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()