View a markdown version of this page

$ l'ultimo N - 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à.

$ l'ultimo N

Nuovo dalla versione 8.0.1.

L'$lastNoperatore in Amazon DocumentDB restituisce gli ultimi N elementi. Se utilizzato come accumulatore in una $group fase, restituisce un array degli ultimi N valori in ciascun gruppo. Se utilizzato come operatore di espressione di matrice, restituisce gli ultimi N elementi di un array.

Parametri

  • input: L'espressione che si risolve nel campo o nell'array da cui restituire i valori.

  • n: un numero intero positivo che specifica quanti valori restituire. Se utilizzato come accumulatore in uno $group stage, n può anche essere un'espressione, purché si risolva in un numero intero positivo in base al campo del gruppo. _id

Esempio (MongoDB Shell)

L'esempio seguente mostra come utilizzare l'$lastNaccumulatore per recuperare le ultime due quantità per ogni articolo durante l'aggregazione.

Nota

$lastNseleziona i valori nell'ordine in cui i documenti arrivano alla fase. $group Per restituire gli ultimi N valori per un ordine specifico (ad esempio, per data o punteggio), aggiungi una $sort fase precedente. $group

Crea documenti di esempio

db.sales.insertMany([ { item: "abc", quantity: 10, date: ISODate("2023-01-01") }, { item: "abc", quantity: 5, date: ISODate("2023-01-02") }, { item: "abc", quantity: 8, date: ISODate("2023-01-03") }, { item: "xyz", quantity: 15, date: ISODate("2023-01-01") }, { item: "xyz", quantity: 7, date: ISODate("2023-01-02") }, { item: "xyz", quantity: 3, date: ISODate("2023-01-03") } ]);

Esempio di interrogazione

db.sales.aggregate([ { $group: { _id: "$item", lastTwoQuantities: { $lastN: { input: "$quantity", n: 2 } } } } ]);

Output

[ { "_id": "abc", "lastTwoQuantities": [5, 8] }, { "_id": "xyz", "lastTwoQuantities": [7, 3] } ]

Esempio di utilizzo delle espressioni (MongoDB Shell)

L'$lastNoperatore può essere utilizzato anche come espressione all'interno di uno $project stage per restituire gli ultimi N elementi di un campo di matrice.

Crea documenti di esempio

db.inventory.insertMany([ { _id: 1, item: "abc", tags: ["red", "green", "blue", "yellow", "purple"] }, { _id: 2, item: "xyz", tags: ["alpha", "beta", "gamma"] } ]);

Esempio di interrogazione

db.inventory.aggregate([ { $project: { lastThreeTags: { $lastN: { input: "$tags", n: 3 } } }} ]);

Output

[ { "_id": 1, "lastThreeTags": ["blue", "yellow", "purple"] }, { "_id": 2, "lastThreeTags": ["alpha", "beta", "gamma"] } ]

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

Nuovo dalla versione 8.0.2.

L'$lastNoperatore può essere utilizzato anche come operatore di finestra nello $setWindowFields stage. In questo contesto, restituisce un array contenente fino agli ultimi n valori per i documenti in ogni finestra. Si specifica l'operatore sotto il output campo e, facoltativamente, si definiscono i confini della finestra con un window documento.

Nota

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

Crea documenti di esempio

db.stockPrices.insertMany([ { _id: 1, ticker: "ABC", hour: 1, price: 50 }, { _id: 2, ticker: "ABC", hour: 2, price: 45 }, { _id: 3, ticker: "ABC", hour: 3, price: 60 }, { _id: 4, ticker: "ABC", hour: 4, price: 40 }, { _id: 5, ticker: "XYZ", hour: 1, price: 30 }, { _id: 6, ticker: "XYZ", hour: 2, price: 35 }, { _id: 7, ticker: "XYZ", hour: 3, price: 25 } ]);

Esempio di interrogazione

L'esempio seguente suddivide i documenti in baseticker, ordina ogni partizione in base hour e restituisce i due prezzi più recenti visualizzati dall'inizio della partizione fino al documento corrente.

db.stockPrices.aggregate([ { $setWindowFields: { partitionBy: "$ticker", sortBy: { hour: 1 }, output: { lastTwoSoFar: { $lastN: { input: "$price", n: 2 }, window: { documents: ["unbounded", "current"] } } } } } ]);

Output

[ { "_id": 1, "ticker": "ABC", "hour": 1, "price": 50, "lastTwoSoFar": [50] }, { "_id": 2, "ticker": "ABC", "hour": 2, "price": 45, "lastTwoSoFar": [50, 45] }, { "_id": 3, "ticker": "ABC", "hour": 3, "price": 60, "lastTwoSoFar": [45, 60] }, { "_id": 4, "ticker": "ABC", "hour": 4, "price": 40, "lastTwoSoFar": [60, 40] }, { "_id": 5, "ticker": "XYZ", "hour": 1, "price": 30, "lastTwoSoFar": [30] }, { "_id": 6, "ticker": "XYZ", "hour": 2, "price": 35, "lastTwoSoFar": [30, 35] }, { "_id": 7, "ticker": "XYZ", "hour": 3, "price": 25, "lastTwoSoFar": [35, 25] } ]

Ogni documento è arricchito con lastTwoSoFar gli ultimi due price valori all'interno della finestra (in ordine). hour

Esempi di codice

Per visualizzare un esempio di codice per l'utilizzo $lastN dell'operatore, scegli la scheda corrispondente alla lingua che desideri utilizzare. Gli esempi seguenti mostrano l'uso dell'accumulatore (in$group), l'uso delle espressioni (in$project) e l'uso dell'operatore di finestra (in$setWindowFields):

Node.js
const { MongoClient } = require('mongodb'); async function example() { const client = new MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'); try { await client.connect(); const db = client.db('test'); // Accumulator usage: last N values per group const sales = db.collection('sales'); await sales.insertMany([ { item: "abc", quantity: 10, date: new Date("2023-01-01") }, { item: "abc", quantity: 5, date: new Date("2023-01-02") }, { item: "abc", quantity: 8, date: new Date("2023-01-03") }, { item: "xyz", quantity: 15, date: new Date("2023-01-01") }, { item: "xyz", quantity: 7, date: new Date("2023-01-02") }, { item: "xyz", quantity: 3, date: new Date("2023-01-03") } ]); const accumulatorResult = await sales.aggregate([ { $group: { _id: "$item", lastTwoQuantities: { $lastN: { input: "$quantity", n: 2 } } } } ]).toArray(); console.log('Accumulator result:', accumulatorResult); // Expression usage: last N elements of an array field const inventory = db.collection('inventory'); await inventory.insertMany([ { _id: 1, item: "abc", tags: ["red", "green", "blue", "yellow", "purple"] }, { _id: 2, item: "xyz", tags: ["alpha", "beta", "gamma"] } ]); const expressionResult = await inventory.aggregate([ { $project: { lastThreeTags: { $lastN: { input: "$tags", n: 3 } } } } ]).toArray(); console.log('Expression result:', expressionResult); // Window operator usage: last N values over a window in each partition const stockPrices = db.collection('stockPrices'); await stockPrices.insertMany([ { _id: 1, ticker: "ABC", hour: 1, price: 50 }, { _id: 2, ticker: "ABC", hour: 2, price: 45 }, { _id: 3, ticker: "ABC", hour: 3, price: 60 }, { _id: 4, ticker: "ABC", hour: 4, price: 40 }, { _id: 5, ticker: "XYZ", hour: 1, price: 30 }, { _id: 6, ticker: "XYZ", hour: 2, price: 35 }, { _id: 7, ticker: "XYZ", hour: 3, price: 25 } ]); const windowResult = await stockPrices.aggregate([ { $setWindowFields: { partitionBy: "$ticker", sortBy: { hour: 1 }, output: { lastTwoSoFar: { $lastN: { input: "$price", n: 2 }, window: { documents: ["unbounded", "current"] } } } } } ]).toArray(); console.log('Window result:', windowResult); } finally { await client.close(); } } example();
Python
from pymongo import MongoClient from datetime import datetime def example(): client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false') try: db = client['test'] # Accumulator usage: last N values per group sales = db['sales'] sales.insert_many([ { 'item': 'abc', 'quantity': 10, 'date': datetime(2023, 1, 1) }, { 'item': 'abc', 'quantity': 5, 'date': datetime(2023, 1, 2) }, { 'item': 'abc', 'quantity': 8, 'date': datetime(2023, 1, 3) }, { 'item': 'xyz', 'quantity': 15, 'date': datetime(2023, 1, 1) }, { 'item': 'xyz', 'quantity': 7, 'date': datetime(2023, 1, 2) }, { 'item': 'xyz', 'quantity': 3, 'date': datetime(2023, 1, 3) } ]) accumulator_result = list(sales.aggregate([ { '$group': { '_id': '$item', 'lastTwoQuantities': { '$lastN': { 'input': '$quantity', 'n': 2 } } } } ])) print('Accumulator result:', accumulator_result) # Expression usage: last N elements of an array field inventory = db['inventory'] inventory.insert_many([ { '_id': 1, 'item': 'abc', 'tags': ['red', 'green', 'blue', 'yellow', 'purple'] }, { '_id': 2, 'item': 'xyz', 'tags': ['alpha', 'beta', 'gamma'] } ]) expression_result = list(inventory.aggregate([ { '$project': { 'lastThreeTags': { '$lastN': { 'input': '$tags', 'n': 3 } } } } ])) print('Expression result:', expression_result) # Window operator usage: last N values over a window in each partition stock_prices = db['stockPrices'] stock_prices.insert_many([ { '_id': 1, 'ticker': 'ABC', 'hour': 1, 'price': 50 }, { '_id': 2, 'ticker': 'ABC', 'hour': 2, 'price': 45 }, { '_id': 3, 'ticker': 'ABC', 'hour': 3, 'price': 60 }, { '_id': 4, 'ticker': 'ABC', 'hour': 4, 'price': 40 }, { '_id': 5, 'ticker': 'XYZ', 'hour': 1, 'price': 30 }, { '_id': 6, 'ticker': 'XYZ', 'hour': 2, 'price': 35 }, { '_id': 7, 'ticker': 'XYZ', 'hour': 3, 'price': 25 } ]) window_result = list(stock_prices.aggregate([ { '$setWindowFields': { 'partitionBy': '$ticker', 'sortBy': { 'hour': 1 }, 'output': { 'lastTwoSoFar': { '$lastN': { 'input': '$price', 'n': 2 }, 'window': { 'documents': ['unbounded', 'current'] } } } } } ])) print('Window result:', window_result) finally: client.close() example()