기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
$last
Amazon DocumentDB의 $last 연산자는 쿼리 기준과 일치하는 배열의 마지막 요소를 반환하는 데 사용됩니다. 특정 조건을 충족하는 배열에서 가장 최근 또는 마지막 요소를 검색하는 데 특히 유용합니다.
파라미터
예제(MongoDB 쉘)
다음 예제에서는 연$last산자를와 함께 사용하여 특정 조건(예: 제목이 '과학')을 충족하는 배열에서 마지막 요소를 $filter 검색하는 방법을 보여줍니다.
샘플 문서 생성
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 }
]
}
]);
쿼리 예제
db.collection.aggregate([
{ $match: { name: "John" } },
{
$project: {
name: 1,
lastScienceScore: {
$last: {
$filter: {
input: "$scores",
as: "score",
cond: { $eq: ["$$score.subject", "science"] }
}
}
}
}
}
]);
출력
[
{
_id: 1,
name: 'John',
lastScienceScore: { subject: 'science', score: 90 }
}
]
창 연산자 사용 예제(MongoDB Shell)
버전 8.0.2에서 새로 추가되었습니다.
연$last산자는 $setWindowFields 스테이지에서 창 연산자로 사용할 수도 있습니다. 이 컨텍스트에서는 각 창의 expression 마지막 문서에서의 값을 반환합니다. output 필드 아래에 연산자를 지정하고 선택적으로 window 문서로 창 경계를 정의합니다.
샘플 문서 생성
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 }
]);
쿼리 예제
다음 예제에서는 문서를 기준으로 분할하고ticker, 각 파티션을 기준으로 정렬하고hour, 각 파티션에 기록된 마지막(최신) 가격을 반환합니다.
db.stockPrices.aggregate([
{
$setWindowFields: {
partitionBy: "$ticker",
sortBy: { hour: 1 },
output: {
lastPrice: {
$last: "$price",
window: { documents: ["unbounded", "unbounded"] }
}
}
}
}
]);
출력
[
{ "_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 }
]
각 문서는 창의 마지막 문서(hour파티션의 최신 문서)의 가격lastPrice인 로 보강됩니다.
코드 예제
$last 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다. 다음 예제에서는 표현식 사용량()과 창 연산자 사용량($project)을 모두 보여줍니다$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()