View a markdown version of this page

$bottomN - Amazon DocumentDB

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

$bottomN

バージョン 8.0.1 から新規。

$group ステージの$bottomNアキュムレータを使用して、指定されたソート順序に従ってグループ内の下位 N 要素を返します。グループに含まれる要素が N 未満の場合、 はグループ内のすべての要素$bottomNを返します。

パラメータ

  • n: 正の整数、またはグループごとに返す下位結果の数を指定する 1 に解決される式。

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

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

例 (MongoDB シェル)

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

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

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

クエリの例

db.sales.aggregate([ { $group: { _id: "$item", bottomTwoSales: { $bottomN: { n: 2, sortBy: { quantity: -1 }, output: { quantity: "$quantity", price: "$price" } } } } } ])

出力

[ { "_id": "xyz", "bottomTwoSales": [{ "quantity": 9, "price": 6 }, { "quantity": 3, "price": 12 }] }, { "_id": "abc", "bottomTwoSales": [{ "quantity": 7, "price": 8 }, { "quantity": 5, "price": 10 }] } ]

コードの例

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

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", bottomTwoSales: { $bottomN: { n: 2, 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', 'bottomTwoSales': { '$bottomN': { 'n': 2, '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()