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à.
$last
L'$lastoperatore in Amazon DocumentDB viene utilizzato per restituire l'ultimo elemento di un array che corrisponde ai criteri di interrogazione. È particolarmente utile per recuperare il più recente o l'ultimo elemento di un array che soddisfa una condizione specifica.
Parametri
Esempio (MongoDB Shell)
L'esempio seguente dimostra l'uso dell'$lastoperatore in combinazione con $filter per recuperare l'ultimo elemento da un array che soddisfa una condizione specifica (ad esempio, il soggetto è «scienza»).
Crea documenti di esempio
db.collection.insertMany([
{
"_id": 1,
"name": "John",
"scores": [
{ "subject": "math", "score": 82 },
{ "subject": "english", "score": 85 },
{ "subject": "science", "score": 90 }
]
},
{
"_id": 2,
"name": "Jane",
"scores": [
{ "subject": "math", "score": 92 },
{ "subject": "english", "score": 88 },
{ "subject": "science", "score": 87 }
]
},
{
"_id": 3,
"name": "Bob",
"scores": [
{ "subject": "math", "score": 75 },
{ "subject": "english", "score": 80 },
{ "subject": "science", "score": 85 }
]
}
]);
Esempio di interrogazione
db.collection.aggregate([
{ $match: { name: "John" } },
{
$project: {
name: 1,
lastScienceScore: {
$last: {
$filter: {
input: "$scores",
as: "score",
cond: { $eq: ["$$score.subject", "science"] }
}
}
}
}
}
]);
Output
[
{
_id: 1,
name: 'John',
lastScienceScore: { subject: 'science', score: 90 }
}
]
Esempio di utilizzo dell'operatore di finestra (MongoDB Shell)
Nuovo dalla versione 8.0.2.
L'$lastoperatore può essere utilizzato anche come operatore di finestra nello $setWindowFields stage. In questo contesto, restituisce il valore expression dell'ultimo documento in ogni finestra. Si specifica l'operatore sotto il output campo e, facoltativamente, si definiscono i confini della finestra con un window documento.
Create 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 l'ultimo (ultimo) prezzo registrato in ciascuna partizione.
db.stockPrices.aggregate([
{
$setWindowFields: {
partitionBy: "$ticker",
sortBy: { hour: 1 },
output: {
lastPrice: {
$last: "$price",
window: { documents: ["unbounded", "unbounded"] }
}
}
}
}
]);
Output
[
{ "_id": 1, "ticker": "ABC", "hour": 1, "price": 50, "lastPrice": 40 },
{ "_id": 2, "ticker": "ABC", "hour": 2, "price": 45, "lastPrice": 40 },
{ "_id": 3, "ticker": "ABC", "hour": 3, "price": 60, "lastPrice": 40 },
{ "_id": 4, "ticker": "ABC", "hour": 4, "price": 40, "lastPrice": 40 },
{ "_id": 5, "ticker": "XYZ", "hour": 1, "price": 30, "lastPrice": 25 },
{ "_id": 6, "ticker": "XYZ", "hour": 2, "price": 35, "lastPrice": 25 },
{ "_id": 7, "ticker": "XYZ", "hour": 3, "price": 25, "lastPrice": 25 }
]
A ogni documento viene aggiunto il lastPrice prezzo dell'ultimo documento nella relativa finestra (l'ultimo nella partizione). hour
Esempi di codice
Per visualizzare un esempio di codice per l'utilizzo $last dell'operatore, scegli la scheda corrispondente alla lingua che desideri utilizzare. Gli esempi seguenti mostrano sia l'utilizzo delle espressioni (in$project) che l'uso dell'operatore di finestra (in$setWindowFields):
- Node.js
-
const { MongoClient } = require('mongodb');
async function example() {
const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
const db = client.db('test');
// Expression usage: last element of a filtered array
const collection = db.collection('collection');
await collection.insertMany([
{
_id: 1,
name: "John",
scores: [
{ subject: "math", score: 82 },
{ subject: "english", score: 85 },
{ subject: "science", score: 90 }
]
},
{
_id: 2,
name: "Jane",
scores: [
{ subject: "math", score: 92 },
{ subject: "english", score: 88 },
{ subject: "science", score: 87 }
]
},
{
_id: 3,
name: "Bob",
scores: [
{ subject: "math", score: 75 },
{ subject: "english", score: 80 },
{ subject: "science", score: 85 }
]
}
]);
const expressionResult = await collection.aggregate([
{ $match: { name: "John" } },
{
$project: {
name: 1,
lastScienceScore: {
$last: {
$filter: {
input: "$scores",
as: "score",
cond: { $eq: ["$$score.subject", "science"] }
}
}
}
}
}
]).toArray();
console.log('Expression result:', JSON.stringify(expressionResult, null, 2));
// Window operator usage: last value within 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: {
lastPrice: {
$last: "$price",
window: { documents: ["unbounded", "unbounded"] }
}
}
}
}
]).toArray();
console.log('Window result:', JSON.stringify(windowResult, null, 2));
await client.close();
}
example();
- Python
-
from pymongo import MongoClient
def example():
client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client.test
# Expression usage: last element of a filtered array
collection = db.collection
collection.insert_many([
{
"_id": 1,
"name": "John",
"scores": [
{ "subject": "math", "score": 82 },
{ "subject": "english", "score": 85 },
{ "subject": "science", "score": 90 }
]
},
{
"_id": 2,
"name": "Jane",
"scores": [
{ "subject": "math", "score": 92 },
{ "subject": "english", "score": 88 },
{ "subject": "science", "score": 87 }
]
},
{
"_id": 3,
"name": "Bob",
"scores": [
{ "subject": "math", "score": 75 },
{ "subject": "english", "score": 80 },
{ "subject": "science", "score": 85 }
]
}
])
expression_pipeline = [
{ "$match": { "name": "John" } },
{
"$project": {
"name": 1,
"lastScienceScore": {
"$last": {
"$filter": {
"input": "$scores",
"as": "score",
"cond": { "$eq": ["$$score.subject", "science"] }
}
}
}
}
}
]
expression_result = list(collection.aggregate(expression_pipeline))
print('Expression result:', expression_result)
# Window operator usage: last value within 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_pipeline = [
{
"$setWindowFields": {
"partitionBy": "$ticker",
"sortBy": { "hour": 1 },
"output": {
"lastPrice": {
"$last": "$price",
"window": { "documents": ["unbounded", "unbounded"] }
}
}
}
}
]
window_result = list(stock_prices.aggregate(window_pipeline))
print('Window result:', window_result)
client.close()
example()