MongoDB 컬렉션에서 가장 오래된 게시물과 가장 최신 게시물을 찾으려면 sort() 메서드를 활용하면 됩니다. 예를 들어 'UserPostDate'라는 날짜 필드를 가진 문서가 있고, 이 중에서 가장 오래된 게시물과 가장 최신 게시물을 각각 조회해야 하는 상황을 가정해 보겠습니다.
1. 샘플 컬렉션 생성하기
먼저 테스트용 문서들을 포함하는 컬렉션을 생성합니다. insertOne() 메서드를 사용해 사용자별 게시물 데이터를 순차적으로 삽입합니다.
>db.getOldestAndYoungestPostDemo.insertOne({"UserId":"Larry@123","UserName":"Larry","UserPostDate":new ISODate('2019-03-27 12:00:00')});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9a700f15e86fd1496b38ab")
}
>db.getOldestAndYoungestPostDemo.insertOne({"UserId":"Sam@897","UserName":"Sam","UserPostDate":new ISODate('2012-06-17 11:40:30')});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9a703815e86fd1496b38ac")
}
>db.getOldestAndYoungestPostDemo.insertOne({"UserId":"David@777","UserName":"David","UserPostDate":new ISODate('2018-01-31 10:45:35')});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9a705e15e86fd1496b38ad")
}
>db.getOldestAndYoungestPostDemo.insertOne({"UserId":"Chris@909","UserName":"Chris","UserPostDate":new ISODate('2017-04-14 04:12:04')});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9a708915e86fd1496b38ae")
}2. 전체 문서 확인하기
find() 메서드를 사용하면 컬렉션에 저장된 모든 문서를 확인할 수 있습니다. pretty()를 함께 사용하면 결과가 보기 좋게 정렬되어 출력됩니다.
> db.getOldestAndYoungestPostDemo.find().pretty();
위 쿼리를 실행하면 다음과 같은 출력 결과를 얻을 수 있습니다.
{
"_id" : ObjectId("5c9a700f15e86fd1496b38ab"),
"UserId" : "Larry@123",
"UserName" : "Larry",
"UserPostDate" : ISODate("2019-03-27T12:00:00Z")
}
{
"_id" : ObjectId("5c9a703815e86fd1496b38ac"),
"UserId" : "Sam@897",
"UserName" : "Sam",
"UserPostDate" : ISODate("2012-06-17T11:40:30Z")
}
{
"_id" : ObjectId("5c9a705e15e86fd1496b38ad"),
"UserId" : "David@777",
"UserName" : "David",
"UserPostDate" : ISODate("2018-01-31T10:45:35Z")
}
{
"_id" : ObjectId("5c9a708915e86fd1496b38ae"),
"UserId" : "Chris@909",
"UserName" : "Chris",
"UserPostDate" : ISODate("2017-04-14T04:12:04Z")
}3. 가장 오래된 게시물 조회하기
가장 오래된 게시물을 찾으려면 sort()에 필드 값을 1(오름차순)로 지정하고, limit(1)로 결과 개수를 하나로 제한하면 됩니다. 오름차순 정렬 시 가장 앞에 위치하는 문서가 곧 가장 오래된 게시물입니다.
> db.getOldestAndYoungestPostDemo.find().sort({ "UserPostDate" : 1 }).limit(1);실행 결과는 다음과 같습니다.
{ "_id" : ObjectId("5c9a703815e86fd1496b38ac"), "UserId" : "Sam@897", "UserName" : "Sam", "UserPostDate" : ISODate("2012-06-17T11:40:30Z") }4. 가장 최신 게시물 조회하기
반대로 가장 최신(최근) 게시물을 찾으려면 sort()에 필드 값을 -1(내림차순)로 지정하고 limit(1)을 적용합니다. 내림차순 정렬 시 첫 번째 문서가 가장 최근에 작성된 게시물입니다.
> db.getOldestAndYoungestPostDemo.find().sort({ "UserPostDate" : -1 }).limit(1);실행 결과는 다음과 같습니다.
{ "_id" : ObjectId("5c9a700f15e86fd1496b38ab"), "UserId" : "Larry@123", "UserName" : "Larry", "UserPostDate" : ISODate("2019-03-27T12:00:00Z") }정리
MongoDB에서 특정 날짜 필드 기준으로 최솟값(가장 오래된 데이터) 또는 최댓값(가장 최신 데이터)을 구하는 것은 sort()와 limit(1)의 조합으로 간단히 해결할 수 있습니다. 오름차순(1)은 가장 오래된 문서를, 내림차순(-1)은 가장 최신 문서를 반환한다는 점만 기억하면 됩니다. 대량의 데이터를 다룰 때는 UserPostDate 필드에 인덱스를 생성해 두면 정렬 성능을 크게 향상시킬 수 있습니다.