MongoDB에서 컬렉션에 저장된 문서 중 특정 키(필드)의 값만 가져오고 싶을 때가 있습니다. 이럴 때는 find() 메서드에 프로젝션(projection) 옵션을 활용하면 됩니다.
기본 문법
키 이름으로 값을 검색하려면 아래와 같은 문법을 사용합니다.
db.yourCollectionName.find({}, {"yourFieldName": 1}).pretty();여기서 두 번째 인자인 {"yourFieldName": 1}이 프로젝션 부분입니다. 값이 1이면 해당 필드를 포함하고, 0이면 제외한다는 의미입니다. 참고로 _id 필드는 명시하지 않아도 기본적으로 항상 함께 반환됩니다.
예제용 컬렉션 생성하기
문법을 실제로 이해하기 위해 샘플 데이터가 담긴 컬렉션을 먼저 만들어 보겠습니다. 아래 쿼리는 retrieveValueFromAKeyDemo라는 컬렉션에 고객 정보 문서를 세 개 삽입합니다.
> db.retrieveValueFromAKeyDemo.insertOne({"CustomerName":"Larry","CustomerAge":21,"CustomerCountryName":"US"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9163b5a56efcc0f9e69048")
}
> db.retrieveValueFromAKeyDemo.insertOne({"CustomerName":"Chris","CustomerAge":24,"CustomerCountryName":"AUS"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9163c4a56efcc0f9e69049")
}
> db.retrieveValueFromAKeyDemo.insertOne({"CustomerName":"Mike","CustomerAge":26,"CustomerCountryName":"UK"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9163d3a56efcc0f9e6904a")
}전체 문서 확인하기
먼저 find() 메서드를 사용해 컬렉션의 모든 문서를 출력해 보겠습니다.
> db.retrieveValueFromAKeyDemo.find().pretty();
실행 결과는 다음과 같습니다.
{
"_id" : ObjectId("5c9163b5a56efcc0f9e69048"),
"CustomerName" : "Larry",
"CustomerAge" : 21,
"CustomerCountryName" : "US"
}
{
"_id" : ObjectId("5c9163c4a56efcc0f9e69049"),
"CustomerName" : "Chris",
"CustomerAge" : 24,
"CustomerCountryName" : "AUS"
}
{
"_id" : ObjectId("5c9163d3a56efcc0f9e6904a"),
"CustomerName" : "Mike",
"CustomerAge" : 26,
"CustomerCountryName" : "UK"
}키 이름으로 특정 값만 조회하기
이번에는 키 이름으로 값을 검색하는 핵심 쿼리입니다. 여기서는 'CustomerCountryName' 키의 값만 가져와 보겠습니다.
> db.retrieveValueFromAKeyDemo.find({}, {"CustomerCountryName": 1}).pretty();실행 결과는 다음과 같습니다.
{
"_id" : ObjectId("5c9163b5a56efcc0f9e69048"),
"CustomerCountryName" : "US"
}
{
"_id" : ObjectId("5c9163c4a56efcc0f9e69049"),
"CustomerCountryName" : "AUS"
}
{
"_id" : ObjectId("5c9163d3a56efcc0f9e6904a"),
"CustomerCountryName" : "UK"
}추가 팁: _id 필드 제외하기
결과에서 _id 필드까지 제거하고 싶다면 프로젝션에서 _id: 0으로 설정하면 됩니다.
> db.retrieveValueFromAKeyDemo.find({}, {"_id": 0, "CustomerCountryName": 1}).pretty();이렇게 하면 국가명 값만 깔끔하게 출력됩니다. 프로젝션은 네트워크 전송량을 줄이고 애플리케이션 성능을 높이는 데 유용한 기능이므로, 필요한 필드만 선택적으로 조회하는 습관을 들이는 것이 좋습니다.