MongoDB에서 배열의 마지막 요소 조회하기
MongoDB에서 배열(Array) 필드의 마지막 요소만 추출하고 싶다면 $slice 연산자를 활용하면 됩니다. 핵심은 음수 값 -1을 사용하는 것인데, 이는 배열의 끝에서부터 요소를 세어 마지막 하나만 반환한다는 의미입니다.
기본 문법
db.yourCollectionName.find({}, {yourArrayFieldName: {$slice: -1}});위 문법에서 두 번째 인자인 프로젝션(projection) 부분에 $slice: -1을 지정하면 해당 배열 필드의 마지막 요소 하나만 결과에 포함됩니다.
예제 컬렉션 생성하기
실습을 위해 먼저 학생 이름과 수학 점수 배열을 가진 컬렉션을 만들어 보겠습니다.
> db.getLastElementOfArrayDemo.insertOne({"StudentName":"James","StudentMathScore":[78,68,98]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9d2d71a629b87623db1b2e")
}
> db.getLastElementOfArrayDemo.insertOne({"StudentName":"Chris","StudentMathScore":[88,56,34]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9d2d83a629b87623db1b2f")
}
> db.getLastElementOfArrayDemo.insertOne({"StudentName":"Larry","StudentMathScore":[99]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9d2d8ea629b87623db1b30")
}
> db.getLastElementOfArrayDemo.insertOne({"StudentName":"Robert","StudentMathScore":[90,78,67,66,75,73]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9d2dada629b87623db1b31")
}저장된 전체 문서 확인
find() 메서드와 pretty() 메서드를 함께 사용하면 컬렉션의 모든 문서를 보기 좋게 출력할 수 있습니다.
> db.getLastElementOfArrayDemo.find().pretty();
실행 결과는 다음과 같습니다.
{
"_id" : ObjectId("5c9d2d71a629b87623db1b2e"),
"StudentName" : "James",
"StudentMathScore" : [
78,
68,
98
]
}
{
"_id" : ObjectId("5c9d2d83a629b87623db1b2f"),
"StudentName" : "Chris",
"StudentMathScore" : [
88,
56,
34
]
}
{
"_id" : ObjectId("5c9d2d8ea629b87623db1b30"),
"StudentName" : "Larry",
"StudentMathScore" : [
99
]
}
{
"_id" : ObjectId("5c9d2dada629b87623db1b31"),
"StudentName" : "Robert",
"StudentMathScore" : [
90,
78,
67,
66,
75,
73
]
}$slice로 마지막 요소만 조회하는 쿼리
이제 각 학생 문서에서 수학 점수 배열의 마지막 요소만 가져오는 쿼리를 실행해 보겠습니다.
> db.getLastElementOfArrayDemo.find({}, {StudentMathScore: {$slice: -1}});실행 결과는 다음과 같습니다.
{ "_id" : ObjectId("5c9d2d71a629b87623db1b2e"), "StudentName" : "James", "StudentMathScore" : [ 98 ] }
{ "_id" : ObjectId("5c9d2d83a629b87623db1b2f"), "StudentName" : "Chris", "StudentMathScore" : [ 34 ] }
{ "_id" : ObjectId("5c9d2d8ea629b87623db1b30"), "StudentName" : "Larry", "StudentMathScore" : [ 99 ] }
{ "_id" : ObjectId("5c9d2dada629b87623db1b31"), "StudentName" : "Robert", "StudentMathScore" : [ 73 ] }결과 분석 및 참고 사항
출력 결과를 보면 각 문서의 StudentMathScore 배열이 원래 여러 개의 값을 가지고 있었음에도 불구하고, 마지막 값 하나만 반환된 것을 확인할 수 있습니다. James의 경우 [78, 68, 98] 중 98, Chris의 경우 [88, 56, 34] 중 34, Robert의 경우 여섯 개 값 중 마지막인 73이 반환되었습니다.
$slice 연산자의 동작 방식을 정리하면 다음과 같습니다.
- 양수 n: 배열의 앞에서부터 n개의 요소를 반환합니다.
- 음수 n: 배열의 뒤에서부터 n개의 요소를 반환합니다.
- [skip, limit] 형식: 특정 위치부터 지정한 개수만큼 요소를 건너뛰거나 가져올 수 있습니다.
따라서 배열의 마지막 요소가 필요한 상황이라면 {$slice: -1}을 사용하는 것이 가장 간단하고 효율적인 방법입니다. 이 기능은 최근 시험 점수, 최신 활동 로그 등 배열 끝부분의 데이터만 필요할 때 특히 유용하게 활용됩니다.