Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ / /
Scala드라이버
/

문서

The Scala driver includes two Scala-specific representations for BSON documents. Following the convention from the Scala collections library, there are immutable and mutable implementations of the Document type. The underlying implementations of Document use the type-safe BsonDocument class. The BSON classes are available from the org.mongodb.scala.bson namespace, which includes type aliases and companion objects. These objects should suffice for many use cases, but for advanced use cases you may need to use classes from the org.bson namespace directly.

중요

중복 키 이름

문서 에서 중복된 키 이름과 관련된 서버의 동작은 정의되지 않았습니다. 키 이름이 중복된 문서 가 디코딩되면 운전자 는 중복 키와 관련된 마지막 값을 할당합니다. 이러한 문서 를 저장하면 다른 값이 손실될 수 있습니다.

참고

Scala Document 클래스는 TraversableLike[(String, BsonValue)] 을 구현하고 일반 API 는 Map[String, BsonValue] 값을 미러링합니다. 그러나 Map TraversableLike 구현은 값 유형에 변화가 없기 때문에 엄격한 유형 안전성을 가능하게 합니다.

BsonValue org.bson 라이브러리에 있는 BSON type의 type-safe 표현이며 특정 값 유형을 나타냅니다. 가장 일반적으로 사용되는 값 유형은 다음과 같습니다.

BSON 유형
Scala 유형

Document

org.mongodb.scala.bson.Document

Array

List

Date

Date 또는 int (에포크 이후 밀리초)

Boolean

Boolean

Double

Double

Int32

Integer

Int64

Long

String

String

Binary

Array[Byte]

ObjectId

ObjectId

Null

None

이러한 매핑을 변경하거나 확장할 수 있으며, 프로세스는 다음 섹션에 설명되어 있습니다.

다음 섹션에서는 두 가지 주요 Document 클래스에 대해 설명합니다.

Scala 컬렉션 라이브러리와 마찬가지로 변경할 수 없는 클래스가 기본 클래스입니다. 편의상 org.mongodb.scala.Documentorg.mongodb.scala.bson.Document 로 별칭이 지정되며 org.mongodb.scala.bson.collection.immutable.Document 에서 사용할 수 있습니다.

이 유형의 인스턴스는 모든 사람이 변경할 수 없습니다. 이러한 컬렉션은 생성된 후에는 변경되지 않습니다. 따라서 서로 다른 시점에 동일한 컬렉션 값에 반복적으로 액세스하면 항상 동일한 요소를 가진 컬렉션이 생성된다는 사실을 신뢰할 수 있습니다.

import org.mongodb.scala.bson._
val doc1 = Document("AL" -> BsonString("Alabama"))
val doc2 = doc1 + ("AK" -> BsonString("Alaska"))
val doc3 = doc2 ++ Document("AR" -> BsonString("Arkansas"), "AZ" -> BsonString("Arizona"))

변경 가능한 Document 유형을 가져오려면 org.mongodb.scala.collections.mutable.Document 에서 명시적으로 가져와야 합니다. 변경 가능한 Document 는 제자리에서 업데이트하거나 확장할 수 있습니다. 즉, Document 의 요소를 부작용으로 변경, 추가 또는 제거할 수 있습니다. Scala 컬렉션과 유사하게, 변경 가능한 유형을 처리할 때는 어떤 코드가 어떤 컬렉션을 언제 변경하는지 이해해야 합니다.

import org.mongodb.scala.bson._
import org.mongodb.scala.bson.collection.mutable.Document
val doc = Document("AL" -> BsonString("Alabama"))
val doc1 = doc + ("AK" -> BsonString("Alaska")) // doc not mutated but new doc created
doc1 ++= Document("AR" -> BsonString("Arkansas"),
"AZ" -> BsonString("Arizona")) // doc1 mutated as ++= changes in place.

대부분의 BsonValue 유형에는 Scala 유형으로부터의 명백한 직접 매핑이 있습니다. 예를 들어 StringBsonString 에 매핑하고, IntBsonInt32 에 매핑하며, LongBsonInt64 에 매핑합니다. 편의상 이러한 유형은 Document 유형과 함께 직접 사용할 수 있으며 BsonMagnets 객체의 계약 특성에 의해 변환됩니다. 특정 유형에 대한 범위에 암시적 BsonTransformer 이 있는 한 해당 유형은 BsonValue 로 변환될 수 있습니다.

다음 BsonTransformers 이 기본값 범위에 있습니다.

Scala 유형
BsonValue

Boolean

BsonBoolean

String

BsonString

Array[Byte]

BsonBinary

Regex

BsonRegex

Date

BsonDateTime

ObjectId

BsonObjectId

Int

BsonInt32

Long

BsonInt64

Double

BsonDouble

immutable.Document

BsonDocument

mutable.Document

BsonDocument

Option[T]

BsonValue 여기서 T 에는 BsonTransformer이 있습니다.

Seq[(String, T)]

BsonDocument 여기서 T 에는 BsonTransformer이 있습니다.

Seq[T]

BsonArray 여기서 T 에는 BsonTransformer이 있습니다.

BsonValue

BsonValue

import org.mongodb.scala.Document
val doc1 = Document("AL" -> "Alabama")
val doc2 = doc1 + ("AK" -> "Alaska")
val doc3 = doc2 ++ Document("AR" -> "Arkansas", "population" -> 2.966)

This is achieved by making use of the Magnet Pattern, which you can learn more about in the Magnet Pattern blog post on spray.io.

일반적으로 단일 값이나 키-값 쌍 또는 많은 키 값 쌍(예: BsonValue, (String, BsonValue) 또는 Iterable[(String, BsonValue)])이 예상되는 API에서는 다음이 될 수 있는 모든 것이 필요합니다. 올바른 유형을 준수하는 데 필요한 암시적 변환을 처리하는 CanBeX 트레이트를 통해 유형을 지정합니다. 이러한 특성은 CanBeBsonValue, CanBeBsonElementCanBeBsonElements 입니다.

한 가지 예로 Document 또는 값 목록에 키-값 쌍을 추가하는 것을 들 수 있습니다.

val doc1 = Document("AL" -> "Alabama")
val doc2 = Document("codes" -> List("AL", "AK", "AR"))

드라이버에는 Bson 이라는 작지만 강력한 인터페이스도 포함되어 있습니다. 드라이버 자체에 포함되어 있든 타사에서 제공하든 BSON 문서를 나타내는 모든 클래스는 이 인터페이스를 구현할 수 있으며 BSON 문서가 필요한 상위 수준 API의 모든 위치에서 사용할 수 있습니다. 예를 들면 다음과 같습니다.

collection.find(Document("x" -> 1))
collection.find(Filters.eq("x", 1))

돌아가기

BSON 구현

이 페이지의 내용