문서 메뉴

문서 홈애플리케이션 개발MongoDB 드라이버Java 동기화 드라이버

문서

이 페이지의 내용

  • 개요
  • 문서
  • BsonDocument
  • JsonObject
  • BasicDBObject
  • 요약

이 가이드에서는 MongoDB Java 드라이버에서 문서를 사용하는 방법에 대해 설명합니다.

MongoDB 문서는 바이너리 JSON (BSON) 형식의 키/값 필드를 포함하는 데이터 구조입니다. 문서와 문서 필드에 포함된 데이터를 사용하여 데이터를 저장할 수 있을 뿐만 아니라 MongoDB에서 명령이나 쿼리를 실행할 수도 있습니다.

문서의 용어, 구조 및 제한 사항에 대한 자세한 내용은 MongoDB 매뉴얼의 문서 페이지를 참조하세요.

MongoDB Java 드라이버 및 BSON 라이브러리에는 문서에서 BSON 데이터에 액세스하고 조작하는 데 도움이 되는 다음 클래스가 포함되어 있습니다.

이름
패키지
맵 구현 여부
권장 사용법
Document
org.bson
구현함 Map<String, Object>
유연하고 간결한 데이터 표현이 필요한 경우.
BsonDocument
org.bson
구현함 Map<String, BsonValue>
안전한 유형의 API가 필요한 경우.
JsonObject
org.bson.json
아니요
JSON 문자열로만 작업하려는 경우.
BasicDBObject
com.mongodb
아니요
레거시 드라이버 버전에서 애플리케이션을 마이그레이션하는 경우.

애플리케이션에서 이러한 클래스를 모두 사용할 수 있지만 복잡성에 관계없이 동적으로 구조화된 문서를 간결하게 표현할 수 있는 Document 클래스를 사용하는 것이 좋습니다. 느슨한 유형의 값을 사용할 수 있게 해주는 Map<String, Object> 인터페이스를 구현합니다.

Document 클래스를 사용하면 BSON 문서를 유연하게 표현할 수 있습니다. 이 클래스와 함께 표준 라이브러리의 Java 유형을 사용하여 필드에 액세스하고 조작할 수 있습니다. 자주 사용되는 BSON과 Java 유형 간의 매핑은 다음 표를 참조하세요.

BSON type
Java 유형
배열
java.util.List
바이너리
org.bson.types.Binary
부울
java.lang.Boolean
날짜
java.util.Date
문서
org.bson.Document
더블
java.lang.Double
Int32
java.lang.Integer
Int64
java.lang.Long
Null
null
객체 ID
org.bson.types.ObjectId
문자열
java.lang.String

앞의 매핑 표는 Document 클래스로 작업할 때의 기본 매핑을 보여줍니다. 사용자 지정 코덱을 지정하여 유형 매핑을 사용자 지정할 수 있습니다. 매핑된 유형의 사용자 지정에 대한 자세한 내용은 코덱 사용 가이드를 참조하세요.

다음 코드 스니펫은 여러 가지 필드 유형이 포함된 문서를 나타내는 샘플 Document 인스턴스를 인스턴스화하고 빌드하는 방법을 보여 줍니다.

Document author = new Document("_id", new ObjectId())
.append("name", "Gabriel García Márquez")
.append("dateOfDeath", Date.from(LocalDate.of(2014, 4, 17).atStartOfDay(ZoneId.systemDefault()).toInstant()))
.append("novels", Arrays.asList(
new Document("title", "One Hundred Years of Solitude").append("yearPublished", 1967),
new Document("title", "Chronicle of a Death Foretold").append("yearPublished", 1981),
new Document("title", "Love in the Time of Cholera").append("yearPublished", 1985)));

이 문서를 컬렉션에 삽입하려면 다음과 같이 getCollection() 메서드를 사용하여 컬렉션을 인스턴스화하고 insertOne 작업을 호출합니다.

// MongoClient mongoClient = <code to instantiate your client>;
MongoDatabase database = mongoClient.getDatabase("fundamentals_data");
MongoCollection<Document> collection = database.getCollection("authors");
InsertOneResult result = collection.insertOne(author);

삽입이 성공적으로 수행되면 다음 코드를 사용하여 컬렉션에서 샘플 문서 데이터를 조회할 수 있습니다.

import com.mongodb.client.model.Filters;
// <MongoCollection setup code here>
Document doc = collection.find(Filters.eq("name", "Gabriel García Márquez")).first();
if (doc != null) {
System.out.println("_id: " + doc.getObjectId("_id")
+ ", name: " + doc.getString("name")
+ ", dateOfDeath: " + doc.getDate("dateOfDeath"));
doc.getList("novels", Document.class).forEach((novel) -> {
System.out.println("title: " + novel.getString("title")
+ ", yearPublished: " + novel.getInteger("yearPublished"));
});
}

앞에 설명한 코드 샘플에서는 반환된 유형을 확인하고 필드 값을 캐스팅할 수 없는 경우 예외를 발생시키는 헬퍼 메서드를 사용합니다. Map 인터페이스에서 지정한 get() 메서드를 호출하여 필드 값을 Object 유형으로 조회하고 유형 검사를 건너뛸 수 있습니다.

앞의 코드의 출력은 다음과 유사합니다.

_id: 5fb5fad05f734e3794741a35, name: Gabriel García Márquez, dateOfDeath: Thu Apr 17 00:00:00 EDT 2014
title: One Hundred Years of Solitude, yearPublished: 1967
title: Chronicle of a Death Foretold, yearPublished: 1981
title: Love in the Time of Cholera, yearPublished: 1985

MongoDB 데이터 검색 및 조작에 대한 자세한 내용은 CRUD 가이드를 참조하세요.

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

BsonDocument 클래스는 BSON 문서에 액세스하고 조작할 수 있는 안전한 형식의 API를 제공합니다. 각 필드에 대해 BSON type을 Java BSON 라이브러리에서 지정해야 합니다. 자주 사용되는 BSON과 Java BSON 라이브러리 유형 간의 매핑은 다음 표를 참조하세요.

BSON type
Java BSON 라이브러리 유형
배열
org.bson.BsonArray
바이너리
org.bson.BsonBinary
부울
org.bson.Boolean
날짜(긴 값)
org.bson.BsonDateTime
문서
org.bson.BsonDocument
더블
org.bson.BsonDouble
Int32
org.bson.BsonInt32
Int64
org.bson.BsonInt64
Null
org.bson.BsonNull
객체 ID
org.bson.BsonObjectId
문자열
org.bson.BsonString

다음 코드 스니펫은 여러 가지 필드 유형이 포함된 문서를 나타내는 샘플 BsonDocument 인스턴스를 인스턴스화하고 빌드하는 방법을 보여 줍니다.

BsonDocument author = new BsonDocument()
.append("_id", new BsonObjectId())
.append("name", new BsonString("Gabriel García Márquez"))
.append("dateOfDeath", new BsonDateTime(LocalDate.of(2014, 4, 17).atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli()))
.append("novels", new BsonArray(Arrays.asList(
new BsonDocument().append("title", new BsonString("One Hundred Years of Solitude")).append("yearPublished", new BsonInt32(1967)),
new BsonDocument().append("title", new BsonString("Chronicle of a Death Foretold")).append("yearPublished", new BsonInt32(1981)),
new BsonDocument().append("title", new BsonString("Love in the Time of Cholera")).append("yearPublished", new BsonInt32(1985))
)));

이 문서를 컬렉션에 삽입하려면 BsonDocument 클래스를 documentClass 매개 변수로 지정하는 getCollection() 메서드를 사용하여 컬렉션을 인스턴스화합니다. 그런 다음, insertOne 작업을 호출합니다.

// MongoClient mongoClient = <code to instantiate your client>;
MongoDatabase database = mongoClient.getDatabase("fundamentals_data");
MongoCollection<BsonDocument> collection = database.getCollection("authors", BsonDocument.class);
InsertOneResult result = collection.insertOne(author);

삽입이 성공적으로 수행되면 다음 코드를 사용하여 컬렉션에서 샘플 문서 데이터를 조회할 수 있습니다.

import com.mongodb.client.model.Filters;
// <MongoCollection setup code here>
BsonDocument doc = collection.find(Filters.eq("name", "Gabriel García Márquez")).first();
if (doc != null) {
System.out.println("_id: " + doc.getObjectId("_id").getValue()
+ ", name: " + doc.getString("name").getValue()
+ ", dateOfDeath: " + new Date(doc.getDateTime("dateOfDeath").getValue()));
doc.getArray("novels").forEach((novel) -> {
System.out.println("title: " + novel.asDocument().getString("title").getValue()
+ ", yearPublished: " + novel.asDocument().getInt32("yearPublished").getValue());
});
}

위의 코드 샘플에서는 반환된 유형을 확인하고 필드 값을 캐스팅할 수 없는 경우 BsonInvalidOperationException을 발생시키는 헬퍼 메서드를 사용합니다. Map 인터페이스에서 지정한 get() 메서드를 호출하여 필드 값을 BsonValue 유형으로 조회하고 유형 검사를 건너뛸 수 있습니다.

앞의 코드의 출력은 다음과 유사합니다.

_id: 5fb5fad05f734e3794741a35, name: Gabriel García Márquez, dateOfDeath: Thu Apr 17 00:00:00 EDT 2014
title: One Hundred Years of Solitude, yearPublished: 1967
title: Chronicle of a Death Foretold, yearPublished: 1981
title: Love in the Time of Cholera, yearPublished: 1985

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

JsonObject 클래스는 JSON 문자열의 래퍼 역할을 합니다. JSON 데이터로만 작업하려는 경우 JsonObject를 사용하여 불필요한 데이터가 Map 객체로 변환되는 것을 방지할 수 있습니다.

기본적으로 JsonObject확장 JSON 을 저장합니다. JsonObjectCodec 를 지정하고 JsonWriterSettings 객체를 전달하여 JsonObject 에서 JSON 형식을 사용자 지정할 수 있습니다. JSON 형식에 대한 자세한 내용은 확장 JSON 가이드 를 참조하세요. 코덱 지정에 대한 자세한 내용은 코덱 가이드를 참조하세요.

다음 코드 스니펫은 다양한 유형의 키 값 쌍을 포함하는 확장 JSON 문자열을 래핑하는 샘플 JsonObject 인스턴스를 인스턴스화하는 방법을 보여 줍니다.

String ejsonStr = "{\"_id\": {\"$oid\": \"6035210f35bd203721c3eab8\"},"
+ "\"name\": \"Gabriel Garc\\u00eda M\\u00e1rquez\","
+ "\"dateOfDeath\": {\"$date\": \"2014-04-17T04:00:00Z\"},"
+ "\"novels\": ["
+ "{\"title\": \"One Hundred Years of Solitude\",\"yearPublished\": 1967},"
+ "{\"title\": \"Chronicle of a Death Foretold\",\"yearPublished\": 1981},"
+ "{\"title\": \"Love in the Time of Cholera\",\"yearPublished\": 1985}]}";
JsonObject author = new JsonObject(ejsonStr);

이 문서를 컬렉션에 삽입하려면 JsonObject 클래스를 documentClass 매개 변수로 지정하는 getCollection() 메서드를 사용하여 컬렉션을 인스턴스화합니다. 그런 다음, insertOne 작업을 호출합니다.

// MongoClient mongoClient = <code to instantiate your client>;
MongoDatabase database = mongoClient.getDatabase("fundamentals_data");
MongoCollection<JsonObject> collection = database.getCollection("authors", JsonObject.class);
InsertOneResult result = collection.insertOne(author);

삽입이 성공적으로 수행되면 컬렉션에서 샘플 JSON 데이터를 검색할 수 있습니다. Bson을 확장하는 모든 클래스를 사용하여 쿼리를 지정할 수 있지만, 다음과 같이 JsonObject를 사용하여 데이터를 쿼리할 수 있습니다.

// MongoClient mongoClient = <code to instantiate your client>;
JsonObject query = new JsonObject("{\"name\": \"Gabriel Garc\\u00eda M\\u00e1rquez\"}");
JsonObject jsonResult = collection.find(query).first();
if (jsonResult != null) {
System.out.println("query result in extended json format: " + jsonResult.getJson());
}

앞의 코드의 출력은 다음과 유사합니다.

query result in extended json format: {"_id": {"$oid": "6035210f35bd203721c3eab8"}, "name": "Gabriel García Márquez", "dateOfDeath": {"$date": "2014-04-17T04:00:00Z"}, "novels": [{"title": "One Hundred Years of Solitude", "yearPublished": 1967}, {"title": "Chronicle of a Death Foretold", "yearPublished": 1981}, {"title": "Love in the Time of Cholera", "yearPublished": 1985}]}

애플리케이션에서 다른 형식의 JSON 문자열로 작업하려면 JsonObjectCodec 클래스를 JsonWriterSettings와 함께 사용하여 원하는 JSON 형식을 지정할 수 있습니다.

다음 코드 예제 에서는 완화 모드 JSON 문자열을 사용하여 MongoDB 인스턴스를 읽고 쓰고 ObjectId 인스턴스를 16진수 문자열로 출력합니다.

import static org.bson.codecs.configuration.CodecRegistries.fromCodecs;
// MongoClient mongoClient = <code to instantiate your client>;
MongoDatabase database = mongoClient.getDatabase("fundamentals_data");
MongoCollection<JsonObject> collection = database.getCollection("authors", JsonObject.class)
.withCodecRegistry(
fromCodecs(
// define a JsonObjectCodec with a JsonWriterSettings in Relaxed mode
new JsonObjectCodec(JsonWriterSettings
.builder()
.outputMode(JsonMode.RELAXED)
.objectIdConverter((objectId, strictJsonWriter) -> {
strictJsonWriter.writeString(objectId.toHexString());
})
.build())));
JsonObject author = new JsonObject("{\"_id\": \"6035210f35bd203721c3eab8\", "
+ "\"name\": \"Gabriel García Márquez\", "
+ "\"dateOfDeath\": {\"$date\": \"2014-04-17T04:00:00Z\"}, "
+ "\"novels\": [{\"title\": \"One Hundred Years of Solitude\", \"yearPublished\": 1967}, {\"title\": \"Chronicle of a Death Foretold\", \"yearPublished\": 1981}, "
+ "{\"title\": \"Love in the Time of Cholera\", \"yearPublished\": 1985}]}\n");
collection.insertOne(author);
JsonObject query = new JsonObject("{\"name\": \"Gabriel Garc\\u00eda M\\u00e1rquez\"}");
JsonObject jsonResult = collection.find(query).first();
if (jsonResult != null) {
System.out.println("query result in relaxed json format: " + jsonResult.getJson());
}

앞의 코드의 출력은 다음과 유사합니다.

query result in relaxed json format: {"_id": "6035210f35bd203721c3eab8", "name": "Gabriel García Márquez", "dateOfDeath": {"$date": "2014-04-17T04:00:00Z"}, "novels": [{"title": "One Hundred Years of Solitude", "yearPublished": 1967}, {"title": "Chronicle of a Death Foretold", "yearPublished": 1981}, {"title": "Love in the Time of Cholera", "yearPublished": 1985}]}

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

BasicDBObject 클래스를 사용하면 Java 유형을 사용하여 문서 데이터에 액세스하고 조작할 수 있습니다. 다음과 같은 제한 사항으로 인해 이전 드라이버 버전에서 애플리케이션을 마이그레이션하는 경우가 아니라면 이 클래스를 사용하지 않는 것이 좋습니다.

  • BasicDBObjectMap<K, V>를 구현하지 않으므로 Map의 데이터 액세스 및 조작 편의 메서드가 부족합니다.

  • 클래스가 아닌 인터페이스를 DBObject 구현하므로 바이너리 호환성 을 깨지 않고는 API를 확장할 수 없습니다. . 즉, 바이너리 호환성을 깨는 방식으로 인터페이스를 변경한 경우 해당 인터페이스를 사용하는 모든 애플리케이션과 클래스를 다시 컴파일해야 오류 없이 새 버전을 실행할 수 있습니다.

다음 코드 스니펫은 여러 가지 필드 유형이 포함된 문서를 나타내는 샘플 BasicDBObject 인스턴스를 인스턴스화하고 빌드하는 방법을 보여 줍니다.

BasicDBObject author = new BasicDBObject("_id", new ObjectId())
.append("name", "Gabriel García Márquez")
.append("dateOfDeath", Date.from(LocalDate.of(2014, 4, 17).atStartOfDay(ZoneId.systemDefault()).toInstant()))
.append("novels", Arrays.asList(
new BasicDBObject("title", "One Hundred Years of Solitude").append("yearPublished", 1967),
new BasicDBObject("title", "Chronicle of a Death Foretold").append("yearPublished", 1981),
new BasicDBObject("title", "Love in the Time of Cholera").append("yearPublished", 1985)));

이 문서를 컬렉션에 삽입하려면 BasicDBObject 클래스를 documentClass 매개 변수로 지정하는 getCollection() 메서드를 사용하여 컬렉션을 인스턴스화합니다. 그런 다음, insertOne 작업을 호출합니다.

// MongoClient mongoClient = <code to instantiate your client>;
MongoDatabase database = mongoClient.getDatabase("fundamentals_data");
MongoCollection<BasicDBObject> collection = database.getCollection("authors", BasicDBObject.class);
InsertOneResult result = collection.insertOne(author);

삽입이 성공적으로 수행되면 다음 코드를 사용하여 컬렉션에서 샘플 문서 데이터를 조회할 수 있습니다.

import com.mongodb.client.model.Filters;
// <MongoCollection setup code here>
BasicDBObject doc = collection.find(Filters.eq("name", "Gabriel García Márquez")).first();
if (doc != null) {
System.out.println("_id: " + doc.getObjectId("_id")
+ ", name: " + doc.getString("name")
+ ", dateOfDeath: " + doc.getDate("dateOfDeath"));
BasicDBList novels = (BasicDBList) doc.get("novels");
if (novels != null) {
BasicDBObject[] novelArr = novels.toArray(new BasicDBObject[0]);
for (BasicDBObject novel : novelArr) {
System.out.println("title: " + novel.getString("title")
+ ", yearPublished: " + novel.getInt("yearPublished"));
}
}
}

앞에 설명한 코드 샘플에서는 반환된 유형을 확인하고 필드 값을 캐스팅할 수 없는 경우 예외를 발생시키는 헬퍼 메서드를 사용합니다. get() 메서드를 호출하여 값을 Object 유형으로 조회하고 유형 검사를 건너뛸 수 있습니다.

앞의 코드의 출력은 다음과 유사합니다.

_id: 5fb5fad05f734e3794741a35, name: Gabriel García Márquez, dateOfDeath: Thu Apr 17 00:00:00 EDT 2014
title: One Hundred Years of Solitude, yearPublished: 1967
title: Chronicle of a Death Foretold, yearPublished: 1981
title: Love in the Time of Cholera, yearPublished: 1985

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

이 가이드에서는 BSON 데이터로 작업하는 데 사용할 수 있는 클래스에 대한 다음 주제를 다루고 있습니다.

  • MongoDB 문서 작업에 사용할 수 있는 네 가지 Java 클래스와 어떤 클래스를 사용해야 더 좋은지와 그 이유에 대한 설명.

  • 여러 유형을 포함하는 문서 작성, 이러한 문서를 컬렉션에 삽입, 유형이 지정된 필드 검색/액세스에 대한 각 클래스 사용법의 예시 제공.

← 문서 데이터 형식: 확장 JSON