View a markdown version of this page

$ unten - Amazon DocumentDB

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

$ unten

Neu ab Version 8.0.1.

Verwenden Sie den $bottom Akkumulator in der $group Phase, um das Dokument mit dem niedrigsten Rang pro Gruppe gemäß einer bestimmten Sortierreihenfolge zurückzugeben.

Parameter

  • sortBy: Ein Dokument, das die Sortierreihenfolge angibt. Wird 1 für aufsteigend oder -1 für absteigend verwendet.

  • output: Ein Ausdruck, der die Felder angibt, die aus dem untersten Dokument zurückgegeben werden sollen.

Beispiel (MongoDB Shell)

Das folgende Beispiel zeigt, wie der $bottom Akkumulator verwendet wird, um den niedrigsten Umsatz (niedrigste Menge) pro Artikel in einer Verkaufskollektion zu ermitteln.

Erstellen Sie Beispieldokumente

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 } ])

Beispiel für eine Abfrage

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

Ausgabe

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

Beispiel für die Verwendung von Fensteroperatoren (MongoDB Shell)

Neu ab Version 8.0.2.

Der $bottom Operator kann auch als Fensterbediener auf der $setWindowFields Bühne verwendet werden. In diesem Zusammenhang gibt es das Dokument output aus dem Dokument zurück, das unter den Dokumenten in jedem Fenster an unterster Stelle steht (entsprechend den Angaben des OperatorssortBy). Sie geben den Operator unter dem output Feld an und definieren optional die Fenstergrenzen mit einem window Dokument.

Anmerkung

Bei Verwendung als Fensteroperator in $setWindowFields $bottom ist er auf 100 MB an Zwischendaten begrenzt. Eine Operation, die dieses Limit überschreitet, gibt einen Fehler zurück.

Erstellen Sie Beispieldokumente

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 } ]);

Beispiel für eine Abfrage

Das folgende Beispiel partitioniert die Dokumente nachplayer, sortiert jede Partition nach und gibt die Runde mit der niedrigsten Punktzahl zurückround, die vom Anfang der Partition bis zum aktuellen Dokument gesehen wurde.

db.matchScores.aggregate([ { $setWindowFields: { partitionBy: "$player", sortBy: { round: 1 }, output: { worstRoundSoFar: { $bottom: { sortBy: { score: -1 }, output: { round: "$round", score: "$score" } }, window: { documents: ["unbounded", "current"] } } } } } ]);

Ausgabe

[ { "_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 } } ]

Jedes Dokument wird um die Runde mit worstRoundSoFar der niedrigsten Punktzahl innerhalb der Partition bis einschließlich des aktuellen Dokuments erweitert.

Codebeispiele

Um ein Codebeispiel für die Verwendung des $bottom Operators anzuzeigen, wählen Sie die Registerkarte für die Sprache, die Sie verwenden möchten. Die folgenden Beispiele zeigen sowohl die Verwendung des Akkumulators (in$group) als auch die Verwendung von Fensteroperatoren (in$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()