View a markdown version of this page

$top - 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.

$top

Neu ab Version 8.0.1.

Verwenden Sie den $top Akkumulator in der $group Phase, um das Dokument mit dem höchsten 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 obersten Dokument zurückgegeben werden sollen.

Beispiel (MongoDB Shell)

Das folgende Beispiel zeigt, wie der $top Akkumulator verwendet wird, um den Top-Verkauf (höchste 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", topSale: { $top: { sortBy: { quantity: -1 }, output: { quantity: "$quantity", price: "$price" } } } } } ])

Ausgabe

[ { "_id": "xyz", "topSale": { "quantity": 15, "price": 3 } }, { "_id": "abc", "topSale": { "quantity": 10, "price": 5 } } ]

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

Neu ab Version 8.0.2.

Der $top Operator kann auch als Fensterbediener auf der $setWindowFields Bühne verwendet werden. In diesem Zusammenhang gibt er das output Dokument zurück, das unter den Dokumenten in jedem Fenster an oberster 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 $top 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 round und gibt die Runde mit der höchsten Punktzahl vom Anfang der Partition bis zum aktuellen Dokument zurück.

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

Ausgabe

[ { "_id": 1, "player": "Alice", "round": 1, "score": 20, "bestRoundSoFar": { "round": 1, "score": 20 } }, { "_id": 2, "player": "Alice", "round": 2, "score": 35, "bestRoundSoFar": { "round": 2, "score": 35 } }, { "_id": 3, "player": "Alice", "round": 3, "score": 28, "bestRoundSoFar": { "round": 2, "score": 35 } }, { "_id": 4, "player": "Bob", "round": 1, "score": 15, "bestRoundSoFar": { "round": 1, "score": 15 } }, { "_id": 5, "player": "Bob", "round": 2, "score": 40, "bestRoundSoFar": { "round": 2, "score": 40 } } ]

Jedes Dokument wird um die Runde mit bestRoundSoFar der höchsten Punktzahl innerhalb seiner Partition bis einschließlich des aktuellen Dokuments erweitert.

Codebeispiele

Um ein Codebeispiel für die Verwendung des $top 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: top 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", topSale: { $top: { sortBy: { quantity: -1 }, output: { quantity: "$quantity", price: "$price" } } } } } ]).toArray(); console.log('Accumulator result:', accumulatorResult); // Window operator usage: best 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: { bestRoundSoFar: { $top: { 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: top 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', 'topSale': { '$top': { 'sortBy': { 'quantity': -1 }, 'output': { 'quantity': '$quantity', 'price': '$price' } } } } } ])) pprint(accumulator_result) # Window operator usage: best 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': { 'bestRoundSoFar': { '$top': { '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()