AI 에이전트의 경우: 문서 인덱스는 https://www.mongodb.com/ko-kr/docs/llms.txt에서 사용할 수 있으며, 모든 페이지의 마크다운 버전은 어떤 URL 경로에 .md를 추가하여 사용할 수 있습니다.

문서 데이터 형식: POJO

이 가이드에서는 일반적인 이전 Java 객체 또는 POJO로 모델링된 데이터를 저장하고 검색하는 방법을 알아봅니다. POJO는 데이터 캡슐화에 자주 사용되며, 이는 데이터 표현에서 비즈니스 논리를 분리하는 방법입니다.

팁

POJO에 대해 자세히 알아보려면 Plain old Java 객체 위키백과 문서를 참조하세요.

이 가이드의 예시에서는 다음 작업을 수행하는 방법을 알아봅니다.

  • POJO 직렬화 및 역직렬화를 위한 드라이버 구성

  • POJO로 모델링된 데이터를 사용하는 CRUD 작업 수행

이 가이드의 섹션에서는 꽃의 특성을 설명하는 다음 샘플 POJO 클래스를 사용합니다.

public class Flower { private ObjectId id; private String name; private List<String> colors; private Boolean isBlooming; private Float height; // public empty constructor needed for retrieving the POJO public Flower() { } public Flower(String name, Boolean isBlooming, Float height, List<String> colors) { this.name = name; this.isBlooming = isBlooming; this.height = height; this.colors = colors; } public ObjectId getId() { return id; } public void setId(ObjectId id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Boolean getIsBlooming() { return isBlooming; } public void setIsBlooming(Boolean isBlooming) { this.isBlooming = isBlooming; } public Float getHeight() { return height; } public void setHeight(Float height) { this.height = height; } public List<String> getColors() { return colors; } public void setColors(List<String> colors) { this.colors = colors; } @Override public String toString() { return "\nFlower {\n\tid: " + id + "\n\tname: " + name + "\n\tcolors: " + colors + "\n\tisBlooming: " + isBlooming + "\n\theight: " + height + "\n}"; }}

MongoDB 내에서 데이터를 저장하고 검색하기 위해 POJO를 정의할 때는 다음 지침을 .

  • POJO 클래스는 프레임워크에서 클래스를 확장하거나 인터페이스를 구현할 수 없습니다.

  • 데이터를 저장 및 검색하려는 모든 필드를 포함하고 static 또는 transient(으)로 표시되지 않았는지 확인하세요.

  • POJO에 JavaBean 명명 규칙 을 사용하여 공용 게터 또는 세터 메서드를 포함하면 드라이버가 데이터를 직렬화하거나 역직렬화할 때 해당 메서드를 호출합니다. 공용 속성 필드에 대한 getter 또는 setter 메서드를 생략하면 드라이버가 해당 메서드에 직접 액세스하거나 할당합니다.

POJO를 사용하도록 드라이버를 구성하려면 다음 구성 요소를 지정해야 합니다:

  • PojoCodecProvider 인스턴스에는 POJO 형식과 BSON 간의 데이터 인코딩 및 디코딩 방법을 정의하는 코덱이 있습니다. 또한 공급자는 코덱이 적용되는 POJO 클래스 또는 패키지를 지정합니다.

  • CodecRegistry 코덱 및 기타 관련 정보가 포함된 인스턴스

  • MongoDatabase 또는 CodecRegistry 을(를) 사용하도록 구성된 MongoCollection 인스턴스

  • MongoCollection 일반 유형에 바인딩된 POJO 문서 클래스로 생성된 TDocument 인스턴스

이전 섹션에 정의된 구성 요구 사항을 충족하려면 다음 단계를 수행하세요.

  1. PojoCodecProvider을(를) 구성합니다. 이 예시에서는 PojoCodecProvider.Builder의 automatic(true) 설정을 사용하여 모든 클래스 및 해당 속성에 코덱을 적용합니다.

    CodecProvider pojoCodecProvider = PojoCodecProvider.builder().automatic(true).build();

    참고

    코덱 제공자에는 직렬화 동작을 추가로 정의하는 ClassModel 및 Convention 인스턴스와 같은 다른 객체도 포함되어 있습니다. 코덱 제공자 및 사용자 지정에 대한 자세한 내용은 POJO 사용자 지정 가이드를 참조하세요.

  2. CodecRegistry에 PojoCodecProvider 인스턴스를 추가합니다. CodecRegistry를 사용하면 하나 이상의 코덱 공급자를 지정하여 POJO 데이터를 인코딩할 수 있습니다. 이 예시에서는 다음 메서드를 호출합니다:

    • fromRegistries() 여러 CodecRegistry 인스턴스를 하나의 인스턴스로 결합하는 방법

    • getDefaultCodecRegistry() 코덱 공급자 목록에서 CodecRegistry 인스턴스 검색

    • fromProviders() PojoCodecProvider에서 CodecRegistry 인스턴스 생성

    다음 코드는 CodecRegistry을(를) 인스턴스화하는 방법입니다.

    // Include the following static imports before your class definitionimport static com.mongodb.MongoClientSettings.getDefaultCodecRegistry;import static org.bson.codecs.configuration.CodecRegistries.fromProviders;import static org.bson.codecs.configuration.CodecRegistries.fromRegistries; ... CodecRegistry pojoCodecRegistry = fromRegistries(getDefaultCodecRegistry(), fromProviders(pojoCodecProvider));
  3. CodecRegistry에서 코덱을 사용하도록 MongoDatabase 또는 MongoCollection 인스턴스를 구성합니다. 코덱을 지정하기 위해 데이터베이스나 컬렉션을 구성할 수 있습니다.

    이 예시에서는 withCodecRegistry() 메서드를 사용하여 sample_pojos (이)라는 MongoDatabase에 CodecRegistry을(를) 설정합니다.

    MongoClient mongoClient = MongoClients.create(uri);MongoDatabase database = mongoClient.getDatabase("sample_pojos").withCodecRegistry(pojoCodecRegistry);
  4. POJO 클래스를 getCollection() 호출에 문서 클래스 매개변수로 전달하고 다음과 같이 MongoCollection 인스턴스의 유형 인수로 지정합니다.

    MongoCollection<Flower> collection = database.getCollection("flowers", Flower.class);

Flower POJO를 사용하도록 MongoCollection 인스턴스를 구성한 후에는 POJO로 모델링된 데이터에 대해 CRUD 작업을 수행할 수 있습니다.

이 예시에서는 Flower POJO를 사용하여 다음 작업을 수행하는 방법을 알아봅니다.

  • flowers 컬렉션에 Flower의 인스턴스를 삽입합니다.

  • 컬렉션 문서 업데이트

  • 컬렉션에서 문서 삭제

  • 컬렉션에 있는 모든 문서 찾기 및 인쇄

// Insert three Flower instancesFlower roseFlower = new Flower("rose", false, 25.4f, Arrays.asList(new String[] {"red", "pink"}));Flower daisyFlower = new Flower("daisy", true, 21.1f, Arrays.asList(new String[] {"purple", "white"}));Flower peonyFlower = new Flower("peony", false, 19.2f, Arrays.asList(new String[] {"red", "green"}));collection.insertMany(Arrays.asList(roseFlower, daisyFlower, peonyFlower)); // Update a documentcollection.updateOne( Filters.lte("height", 22), Updates.addToSet("colors", "pink")); // Delete a documentcollection.deleteOne(Filters.eq("name", "rose")); // Return and print all documents in the collectionList<Flower> flowers = new ArrayList<>();collection.find().into(flowers);System.out.println(flowers);

이 예시에서는 다음 출력을 표시합니다.

[Flower { id: 65b178ffa38ac42044ca1573 name: daisy colors: [purple, white, pink] isBlooming: true height: 21.1},Flower { id: 65b178ffa38ac42044ca1574 name: peony colors: [red, green] isBlooming: false height: 19.2}]

참고

기본적으로 PojoCodecProvider 는 POJO에서 null 로 설정된 필드를 생략합니다. 이 동작을 지정하는 방법에 대한 자세한 내용은 POJO 사용자 지정 가이드를 참조하세요.

이 섹션에 언급된 메서드 및 클래스에 대한 자세한 내용은 다음 API 문서를 참조하세요.

이 섹션에서는 MongoDB 에 POJO를 저장할 때 발생할 수 있는 질문에 대한 답변을 제공합니다.

아니요, PojoCodecProvider 는 ObjectId를 자동으로 생성합니다.

네. 여러 값을 포함하는 필드 에 @BsonId 주석을 달아 복합 키로 사용합니다. 다음 예시 code 및 date 필드가 있는 EntityKey 클래스를 정의한 다음 이를 Entity POJO에서 _id 필드 로 사용합니다.

public static class EntityKey { @BsonCreator public EntityKey(@BsonProperty("code") String code, @BsonProperty("date") Date date) { this.code = code; this.date = date; } // getters} public static class Entity { @BsonId private final EntityKey key; @BsonCreator public Entity(@BsonProperty("key") EntityKey key) { this.key = key; } // getters and setters}

예, 판별자를 사용하면 됩니다. 자세한 내용은 POJO 사용자 지정 가이드의 판별자 섹션을 참조하세요.

아니요. 네이티브 POJO 코덱은 게터와 세터가 각 필드 에 대해 동일한 수정자를 갖는다고 가정합니다.

예를 들어 다음 메서드는 인코딩 중에 예외를 발생시킵니다.

private String getField();public String setField(String x);

이 예외는 클래스에 대한 코덱이 존재하지 않으므로 클래스에 대한 코덱을 등록해야 함을 의미합니다.