Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

Java로 MongoDB 프로젝션(Projection) 활용하기: 필요한 필드만 조회하는 방법


MongoDB 컬렉션에서 데이터를 조회할 때, 문서 전체가 아닌 필요한 필드만 선택적으로 가져오고 싶은 경우가 많습니다. 이럴 때 사용하는 것이 바로 프로젝션(Projection)입니다. 프로젝션을 활용하면 불필요한 데이터 전송을 줄여 네트워크 트래픽과 메모리 사용량을 절약하고, 애플리케이션 전반의 성능을 향상시킬 수 있습니다.

projection() 메서드란?

Java에서는 find() 메서드의 결과에 projection() 메서드를 호출하여 원하는 필드만 조회할 수 있습니다. 이 메서드에 포함하려는 필드 이름을 인자로 전달하면 됩니다.

projection(Projections.include("name", "age"));

위 코드는 name과 age 필드만 포함한 결과를 반환합니다. 반대로 특정 필드만 제외하고 싶다면 Projections.exclude()를 사용할 수도 있습니다.

예제

다음 Java 예제는 students 컬렉션에서 문서를 읽어오면서, 프로젝션을 적용해 name과 age 필드의 값만 화면에 출력합니다.

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Projections;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.bson.Document;
import com.mongodb.MongoClient;

public class ProjectionExample {
    public static void main( String args[] ) {
        // MongoDB 클라이언트 생성
        MongoClient mongo = new MongoClient( "localhost" , 27017 );
        // 데이터베이스 연결
        MongoDatabase database = mongo.getDatabase("myDatabase");
        // 컬렉션 객체 생성
        MongoCollection<Document> collection = database.getCollection("students");

        Document document1 = new Document("name", "Ram").append("age", 26).append("city", "Hyderabad");
        Document document2 = new Document("name", "Robert").append("age", 27).append("city", "Vishakhapatnam");
        Document document3 = new Document("name", "Rhim").append("age", 30).append("city", "Delhi");

        // 생성한 문서 삽입
        List<Document> list = new ArrayList<Document>();
        list.add(document1);
        list.add(document2);
        list.add(document3);
        collection.insertMany(list);
        System.out.println("Documents Inserted");

        collection = database.getCollection("students");
        // 문서 조회 시 name과 age 필드만 프로젝션으로 가져오기
        FindIterable<Document> iterDoc =
        collection.find().projection(Projections.include("name", "age"));

        Iterator it = iterDoc.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }
}

실행 결과

Documents Inserted
Document{{_id=5e8966533f68506911c946dc, name=Ram, age=26}}
Document{{_id=5e8966533f68506911c946dd, name=Robert, age=27}}
Document{{_id=5e8966533f68506911c946de, name=Rhim, age=30}}

코드 흐름 정리

  1. 클라이언트 생성: MongoClient를 만들어 localhost의 27017 포트에서 실행 중인 MongoDB 서버에 연결합니다.
  2. 컬렉션 준비: myDatabase 데이터베이스의 students 컬렉션 객체를 가져옵니다.
  3. 문서 삽입: name, age, city 필드를 가진 세 개의 문서를 생성한 뒤 insertMany()로 한 번에 삽입합니다.
  4. 프로젝션 조회: find()로 전체 문서를 조회하면서 projection()에 Projections.include("name", "age")를 전달하여 name과 age 필드만 가져옵니다.
  5. 결과 출력: 반복자(iterator)를 사용해 조회된 문서를 하나씩 출력합니다.

주의할 점: _id 필드

실행 결과를 보면 _id 필드는 명시적으로 요청하지 않았음에도 함께 반환되는 것을 확인할 수 있습니다. MongoDB는 기본적으로 _id 필드를 항상 반환하기 때문인데, 이를 제외하고 싶다면 다음과 같이 Projections.excludeId()를 함께 지정하면 됩니다.

collection.find().projection(Projections.include("name", "age", "city")
                             .excludeId());

이처럼 프로젝션을 잘 활용하면 대용량 컬렉션에서도 꼭 필요한 데이터만 효율적으로 처리할 수 있습니다.