View a markdown version of this page

$ zu PN - 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.

$ zu PN

Neu ab Version 8.0.1.

Verwenden Sie den $topN Akkumulator in der $group Phase, um die obersten N Elemente innerhalb einer Gruppe gemäß einer bestimmten Sortierreihenfolge zurückzugeben. Wenn eine Gruppe weniger als N Elemente enthält, werden alle Elemente in der Gruppe $topN zurückgegeben.

Parameter

  • n: Eine positive Ganzzahl oder ein Ausdruck, der in eins aufgelöst wird und angibt, wie viele Top-Ergebnisse pro Gruppe zurückgegeben werden sollen.

  • 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 jedem der N wichtigsten Dokumente zurückgegeben werden sollen.

Beispiel (MongoDB Shell)

Das folgende Beispiel zeigt, wie der $topN Akkumulator verwendet wird, um die beiden besten Verkäufe (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: 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 } ])

Beispiel für eine Abfrage

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

Ausgabe

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

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

Neu ab Version 8.0.2.

Der $topN Operator kann auch als Fensterbediener auf der $setWindowFields Bühne verwendet werden. In diesem Zusammenhang gibt er unter den Dokumenten in jedem Fenster ein Array mit den N Dokumenten output aus den obersten N Dokumenten zurück (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 $topN 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 beiden Runden 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: { topTwoRoundsSoFar: { $topN: { n: 2, sortBy: { score: -1 }, output: { round: "$round", score: "$score" } }, window: { documents: ["unbounded", "current"] } } } } } ]);

Ausgabe

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

Jedes Dokument wird um die beiden Runden mit topTwoRoundsSoFar der höchsten Punktzahl innerhalb der Partition bis einschließlich des aktuellen Dokuments erweitert. Wenn das Fenster weniger als zwei Dokumente enthält, werden alle zurückgegeben.

Codebeispiele

Um ein Codebeispiel für die Verwendung des $topN 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 N documents per group const sales = db.collection('sales'); await 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 } ]); const accumulatorResult = await sales.aggregate([ { $group: { _id: "$item", topTwoSales: { $topN: { n: 2, sortBy: { quantity: -1 }, output: { quantity: "$quantity", price: "$price" } } } } } ]).toArray(); console.log('Accumulator result:', accumulatorResult); // Window operator usage: top two rounds 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: { topTwoRoundsSoFar: { $topN: { n: 2, 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 N documents per group sales = db['sales'] sales.insert_many([ { '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 } ]) accumulator_result = list(sales.aggregate([ { '$group': { '_id': '$item', 'topTwoSales': { '$topN': { 'n': 2, 'sortBy': { 'quantity': -1 }, 'output': { 'quantity': '$quantity', 'price': '$price' } } } } } ])) pprint(accumulator_result) # Window operator usage: top two rounds 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': { 'topTwoRoundsSoFar': { '$topN': { 'n': 2, '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()