翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
$ 下部
バージョン 8.0.1 から新規。
$group ステージの $bottom アキュムレータを使用して、指定されたソート順序に従ってグループごとに最低ランクのドキュメントを返します。
パラメータ
例 (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 } }
]
ウィンドウ演算子の使用例 (MongoDB シェル)
バージョン 8.0.2 の新機能。
$bottom 演算子は、$setWindowFieldsステージのウィンドウ演算子としても使用できます。このコンテキストでは、各ウィンドウのドキュメント間で (オペレータ自身の に従ってsortBy) 下位ランクのドキュメントoutputから を返します。output フィールドで 演算子を指定し、オプションでwindowドキュメントを使用してウィンドウの境界を定義します。
でウィンドウ演算子として使用する場合$setWindowFields、 $bottomは 100 MB の中間データに制限されます。この制限を超えるオペレーションはエラーを返します。
サンプルドキュメントを作成する
db.matchScores.insertMany([
{ _id: 1, player: "Alice", round: 1, score: 20 },
{ _id: 2, player: "Alice", round: 2, score: 35 },
{ _id: 3, player: "Alice", round: 3, score: 28 },
{ _id: 4, player: "Bob", round: 1, score: 15 },
{ _id: 5, player: "Bob", round: 2, score: 40 }
]);
クエリの例
次の例ではplayer、ドキュメントを でパーティション化し、各パーティションを でソートしてround、パーティションの先頭から現在のドキュメントまでの最低スコアのラウンドを返します。
db.matchScores.aggregate([
{
$setWindowFields: {
partitionBy: "$player",
sortBy: { round: 1 },
output: {
worstRoundSoFar: {
$bottom: { sortBy: { score: -1 }, output: { round: "$round", score: "$score" } },
window: { documents: ["unbounded", "current"] }
}
}
}
}
]);
出力
[
{ "_id": 1, "player": "Alice", "round": 1, "score": 20, "worstRoundSoFar": { "round": 1, "score": 20 } },
{ "_id": 2, "player": "Alice", "round": 2, "score": 35, "worstRoundSoFar": { "round": 1, "score": 20 } },
{ "_id": 3, "player": "Alice", "round": 3, "score": 28, "worstRoundSoFar": { "round": 1, "score": 20 } },
{ "_id": 4, "player": "Bob", "round": 1, "score": 15, "worstRoundSoFar": { "round": 1, "score": 15 } },
{ "_id": 5, "player": "Bob", "round": 2, "score": 40, "worstRoundSoFar": { "round": 1, "score": 15 } }
]
各ドキュメントはworstRoundSoFar、現在のドキュメントまで、パーティション内の最も低いスコアのラウンドである で拡張されます。
コードの例
$bottom 演算子を使用するコード例を表示するには、使用する言語のタブを選択します。次の例は、アキュムレータの使用 ( の場合$group) とウィンドウ演算子の使用 ( の場合) の両方を示しています$setWindowFields。
- 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');
// Accumulator usage: bottom document per group
const sales = db.collection('sales');
await 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 }
]);
const accumulatorResult = await sales.aggregate([
{ $group: { _id: "$item", bottomSale: { $bottom: { sortBy: { quantity: -1 }, output: { quantity: "$quantity", price: "$price" } } } } }
]).toArray();
console.log('Accumulator result:', accumulatorResult);
// Window operator usage: worst round so far within each partition
const matchScores = db.collection('matchScores');
await matchScores.insertMany([
{ _id: 1, player: "Alice", round: 1, score: 20 },
{ _id: 2, player: "Alice", round: 2, score: 35 },
{ _id: 3, player: "Alice", round: 3, score: 28 },
{ _id: 4, player: "Bob", round: 1, score: 15 },
{ _id: 5, player: "Bob", round: 2, score: 40 }
]);
const windowResult = await matchScores.aggregate([
{
$setWindowFields: {
partitionBy: "$player",
sortBy: { round: 1 },
output: {
worstRoundSoFar: {
$bottom: { sortBy: { score: -1 }, output: { round: "$round", score: "$score" } },
window: { documents: ["unbounded", "current"] }
}
}
}
}
]).toArray();
console.log('Window result:', windowResult);
} 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']
# Accumulator usage: bottom document per group
sales = db['sales']
sales.insert_many([
{ 'item': 'abc', 'quantity': 10, 'price': 5 },
{ 'item': 'abc', 'quantity': 5, 'price': 8 },
{ 'item': 'xyz', 'quantity': 15, 'price': 3 },
{ 'item': 'xyz', 'quantity': 7, 'price': 6 }
])
accumulator_result = list(sales.aggregate([
{ '$group': { '_id': '$item', 'bottomSale': { '$bottom': { 'sortBy': { 'quantity': -1 }, 'output': { 'quantity': '$quantity', 'price': '$price' } } } } }
]))
pprint(accumulator_result)
# Window operator usage: worst round so far within each partition
match_scores = db['matchScores']
match_scores.insert_many([
{ '_id': 1, 'player': 'Alice', 'round': 1, 'score': 20 },
{ '_id': 2, 'player': 'Alice', 'round': 2, 'score': 35 },
{ '_id': 3, 'player': 'Alice', 'round': 3, 'score': 28 },
{ '_id': 4, 'player': 'Bob', 'round': 1, 'score': 15 },
{ '_id': 5, 'player': 'Bob', 'round': 2, 'score': 40 }
])
window_result = list(match_scores.aggregate([
{
'$setWindowFields': {
'partitionBy': '$player',
'sortBy': { 'round': 1 },
'output': {
'worstRoundSoFar': {
'$bottom': { 'sortBy': { 'score': -1 }, 'output': { 'round': '$round', 'score': '$score' } },
'window': { 'documents': ['unbounded', 'current'] }
}
}
}
}
]))
pprint(window_result)
except Exception as e:
print(f"An error occurred: {e}")
finally:
if client:
client.close()
example()