View a markdown version of this page

$fondo - Amazon DocumentDB

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

$fondo

Nuovo dalla versione 8.0.1.

Usa l'$bottomaccumulatore nella $group fase per restituire il documento con il punteggio più basso per gruppo in base a un ordinamento specificato.

Parametri

  • sortBy: Un documento che specifica l'ordinamento. 1Da utilizzare in ordine crescente o -1 decrescente.

  • output: un'espressione che specifica i campi da restituire dalla parte inferiore del documento.

Esempio (MongoDB Shell)

L'esempio seguente mostra come utilizzare l'$bottomaccumulatore per trovare la vendita più bassa (quantità minima) per articolo in una raccolta di vendite.

Crea documenti di esempio

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

Esempio di interrogazione

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

Output

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

Esempio di utilizzo dell'operatore di finestra (MongoDB Shell)

Nuovo dalla versione 8.0.2.

L'$bottomoperatore può essere utilizzato anche come operatore di finestra nello $setWindowFields stage. In questo contesto, restituisce il documento output dall'ultimo posto (in base a quello dell'operatoresortBy) tra i documenti in ciascuna finestra. Si specifica l'operatore sotto il output campo e, facoltativamente, si definiscono i confini della finestra con un documento. window

Nota

Se utilizzato come operatore di finestra in$setWindowFields, $bottom è limitato a 100 MB di dati intermedi. Un'operazione che supera questo limite restituisce un errore.

Crea documenti di esempio

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

Esempio di interrogazione

L'esempio seguente suddivide i documenti in baseplayer, ordina ogni partizione in base round e restituisce il punteggio più basso visualizzato dall'inizio della partizione fino al documento corrente.

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

Output

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

Ogni documento è arricchito con il punteggio più basso all'worstRoundSoFarinterno della relativa partizione fino al documento corrente incluso.

Esempi di codice

Per visualizzare un esempio di codice per l'utilizzo dell'$bottomoperatore, scegli la scheda corrispondente alla lingua che desideri utilizzare. Gli esempi seguenti mostrano sia l'utilizzo dell'accumulatore (in$group) che l'utilizzo dell'operatore di finestra (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()