MongoDB에서 특정 월 또는 연도(날짜 제외) 조회하는 방법
MongoDB에서 저장된 날짜 데이터의 일(day) 정보는 무시하고 특정 월(month) 또는 연도(year)에 해당하는 문서만 조회해야 하는 경우가 있습니다. 이럴 때는 집계 프레임워크(Aggregation Framework)와 $month 프로젝션 연산자를 조합하면 간단하게 해결할 수 있습니다.
먼저 예제에 사용할 컬렉션을 생성하고 문서를 삽입해 보겠습니다.
1단계: 테스트 컬렉션 생성 및 문서 삽입
> db.specificMonthDemo.insertOne({"StudentName":"Larry","StudentDateOfBirth":new ISODate('1995-01-12')});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cb9a9ca8f1d1b97daf71819")
}
> db.specificMonthDemo.insertOne({"StudentName":"Chris","StudentDateOfBirth":new ISODate('1999-12-31')});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cb9a9db8f1d1b97daf7181a")
}
> db.specificMonthDemo.insertOne({"StudentName":"David","StudentDateOfBirth":new ISODate('2000-06-01')});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cb9a9ee8f1d1b97daf7181b")
}위 명령은 학생 이름(StudentName)과 생년월일(StudentDateOfBirth) 필드를 가진 세 개의 문서를 specificMonthDemo 컬렉션에 추가합니다.
2단계: find() 메서드로 전체 문서 확인
다음은 find() 메서드를 사용해 컬렉션의 모든 문서를 출력하는 쿼리입니다.
> db.specificMonthDemo.find().pretty();
이 쿼리는 다음과 같은 결과를 반환합니다.
{
"_id" : ObjectId("5cb9a9ca8f1d1b97daf71819"),
"StudentName" : "Larry",
"StudentDateOfBirth" : ISODate("1995-01-12T00:00:00Z")
}
{
"_id" : ObjectId("5cb9a9db8f1d1b97daf7181a"),
"StudentName" : "Chris",
"StudentDateOfBirth" : ISODate("1999-12-31T00:00:00Z")
}
{
"_id" : ObjectId("5cb9a9ee8f1d1b97daf7181b"),
"StudentName" : "David",
"StudentDateOfBirth" : ISODate("2000-06-01T00:00:00Z")
}3단계: $month 연산자로 특정 월 조회하기
다음은 날짜 전체가 아닌 특정 월에 해당하는 문서만 추출하는 쿼리입니다. $project 단계에서 생년월일로부터 월 값만 추출한 뒤, $match 단계에서 원하는 월과 일치하는 문서를 필터링합니다.
> db.specificMonthDemo.aggregate([ {$project: {StudentName: 1, StudentDateOfBirth:
{$month: '$StudentDateOfBirth'}}}, {$match: {StudentDateOfBirth: 01}} ]).pretty();실행 결과는 다음과 같습니다.
{
"_id" : ObjectId("5cb9a9ca8f1d1b97daf71819"),
"StudentName" : "Larry",
"StudentDateOfBirth" : 1
}결과를 보면 1월에 태어난 Larry의 문서만 조회된 것을 확인할 수 있습니다. $month 연산자는 ISODate 값에서 월(1~12)을 숫자로 추출하며, 이어지는 $match 단계가 해당 숫자와 일치하는 문서만 남깁니다.
참고: 특정 연도 조회 시에는 $year 연산자 사용
연도를 기준으로 조회하려면 $month 대신 $year 연산자를 사용하면 됩니다. 예를 들어 2000년생 학생을 찾으려면 다음과 같이 작성합니다.
> db.specificMonthDemo.aggregate([
{ $project: { StudentName: 1, BirthYear: { $year: '$StudentDateOfBirth' } } },
{ $match: { BirthYear: 2000 } }
]).pretty();
이처럼 집계 파이프라인의 $project와 $match 단계를 조합하면 날짜의 특정 부분(월, 연도 등)만 기준으로 데이터를 유연하게 조회할 수 있습니다.