View a markdown version of this page

$ unten N - 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 N

Neu ab Version 8.0.1.

Verwenden Sie den $bottomN Akkumulator in der $group Phase, um die untersten 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 $bottomN zurückgegeben.

Parameter

  • n: Eine positive Ganzzahl oder ein Ausdruck, der in eins aufgelöst wird und angibt, wie viele unterste 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 von jedem der unteren N Dokumente zurückgegeben werden sollen.

Beispiel (MongoDB Shell)

Das folgende Beispiel zeigt, wie der $bottomN Akkumulator verwendet wird, um die beiden niedrigsten Verkäufe (niedrigste 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", bottomTwoSales: { $bottomN: { n: 2, sortBy: { quantity: -1 }, output: { quantity: "$quantity", price: "$price" } } } } } ])

Ausgabe

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

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

Neu ab Version 8.0.2.

Der $bottomN Operator kann auch als Fensterbediener auf der $setWindowFields Bühne verwendet werden. In diesem Zusammenhang gibt er unter den Dokumenten in jedem Fenster eine Reihe output von N Dokumenten (entsprechend den Angaben des OperatorssortBy) von unten zurück. 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 $bottomN 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 niedrigsten Punktzahl vom Anfang der Partition bis zum aktuellen Dokument zurück.

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

Ausgabe

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

Jedes Dokument wird um die beiden Runden mit bottomTwoRoundsSoFar der niedrigsten 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 $bottomN 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 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", bottomTwoSales: { $bottomN: { n: 2, sortBy: { quantity: -1 }, output: { quantity: "$quantity", price: "$price" } } } } } ]).toArray(); console.log('Accumulator result:', accumulatorResult); // Window operator usage: bottom 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: { bottomTwoRoundsSoFar: { $bottomN: { 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: bottom 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', 'bottomTwoSales': { '$bottomN': { 'n': 2, 'sortBy': { 'quantity': -1 }, 'output': { 'quantity': '$quantity', 'price': '$price' } } } } } ])) pprint(accumulator_result) # Window operator usage: bottom 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': { 'bottomTwoRoundsSoFar': { '$bottomN': { '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()