本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$底部
8.0.1 版中的新增内容。
使用$group阶段中的$bottom累加器根据指定的排序顺序返回每组排名最低的文档。
参数
示例(MongoDB Shell)
以下示例说明如何使用$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 Shell)
8.0.2 版中的新内容。
该$bottom操作员还可以在$setWindowFields舞台中用作窗口操作员。在这种情况下,它返回每个output窗口中排名最低的文档(根据操作员自己的文档sortBy)。您可以在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()