반환할 필드 지정
개요
이 가이드 에서는 스칼라 운전자 사용하여 프로젝션 사용하여 읽기 작업에서 반환할 필드를 지정하는 방법을 학습 수 있습니다. 프로젝션 은 MongoDB 쿼리 에서 반환하는 필드를 지정하는 문서 입니다.
샘플 데이터
이 가이드 의 예제에서는 restaurants
sample_restaurants
Atlas 샘플 데이터 세트의 데이터베이스 에 있는 컬렉션 사용합니다. 스칼라 애플리케이션 에서 이 컬렉션 액세스 하려면 MongoClient
Atlas cluster 에 연결하는 를 만들고 및 변수에 다음 값을 할당합니다.database
collection
val database: MongoDatabase = client.getDatabase("sample_restaurants") val collection: MongoCollection[Document] = database.getCollection("restaurants")
무료 MongoDB Atlas cluster 를 생성하고 샘플 데이터 세트를 로드하는 방법을 학습 보려면 Atlas 시작하기 가이드 를 참조하세요.
프로젝션 유형
프로젝션을 사용하여 반환 문서에 포함할 필드를 지정하거나 제외할 필드를 지정할 수 있습니다. _id
필드를 제외하지 않는 한 포함 및 제외 문을 단일 프로젝션에서 결합할 수 없습니다.
포함할 필드 지정
결과에 포함할 필드를 지정하려면 projection()
메서드를 find()
메서드에 연결합니다. Projections
클래스는 포함할 필드를 설정하다 데 사용할 수 있는 include()
헬퍼 메서드를 제공합니다.
다음 예시 find()
메서드를 사용하여 name
필드 값이 "Emerald Pub"
인 모든 레스토랑을 찾습니다. 그런 다음 이 코드는 projection()
및 include()
메서드를 호출하여 일치하는 문서의 name
, cuisine
, borough
필드만 반환하도록 찾기 작업을 지시합니다.
collection .find(equal("name", "Emerald Pub")) .projection(include("name", "cuisine", "borough")) .subscribe((doc: Document) => println(doc.toJson()), (e: Throwable) => println(s"There was an error: $e"))
{"_id": {"$oid": "..."}, "borough": "Manhattan", "cuisine": "American", "name": "Emerald Pub"} {"_id": {"$oid": "..."}, "borough": "Queens", "cuisine": "American", "name": "Emerald Pub"}
프로젝션을 사용하여 반환 문서에 포함할 필드를 지정하면 기본적으로 _id
필드도 포함됩니다. 다른 모든 필드는 암시적으로 제외됩니다. 반환 문서에서 _id
필드를 제거하려면 해당 필드를 명시적으로 제외해야 합니다.
필드 제외 _id
포함할 필드를 지정할 때 반환된 문서 에서 _id
필드 제외할 수도 있습니다. Projections
클래스는 이 필드 생략하는 데 사용할 수 있는 excludeId()
헬퍼 메서드를 제공합니다.
다음 예시 에서는 이전 예시 와 동일한 쿼리 를 수행하지만 프로젝션 에서 _id
필드 를 제외합니다.
collection .find(equal("name", "Emerald Pub")) .projection(fields(include("name", "cuisine", "borough"), excludeId())) .subscribe((doc: Document) => println(doc.toJson()), (e: Throwable) => println(s"There was an error: $e"))
{"borough": "Manhattan", "cuisine": "American", "name": "Emerald Pub"} {"borough": "Queens", "cuisine": "American", "name": "Emerald Pub"}
제외할 필드 지정
결과에서 제외할 필드를 지정하려면 projection()
메서드를 find()
메서드에 연결합니다. Projections
클래스는 제외할 필드를 설정하다 데 사용할 수 있는 exclude()
헬퍼 메서드를 제공합니다.
다음 예시 find()
메서드를 사용하여 name
필드 값이 "Emerald Pub"
인 모든 레스토랑을 찾습니다. 그런 다음 이 코드는 projection()
및 exclude()
메서드를 호출하여 찾기 작업이 결과에서 name
및 address
필드를 생략하도록 지시합니다.
collection .find(equal("name", "Emerald Pub")) .projection(exclude("name", "address")) .subscribe((doc: Document) => println(doc.toJson()), (e: Throwable) => println(s"There was an error: $e"))
{"_id": {"$oid": "..."}, "borough": "Manhattan", "cuisine": "American", "grades": [...], "restaurant_id": "40367329"} {"_id": {"$oid": "..."}, "borough": "Queens", "cuisine": "American", "grades": [...], "restaurant_id": "40668598"}
프로젝션을 사용하여 제외할 필드를 지정하면 지정되지 않은 모든 필드가 반환 문서에 암시적으로 포함됩니다.
추가 정보
프로젝션에 학습 보려면 MongoDB Server 매뉴얼의 프로젝트 필드 가이드 를 참조하세요.
API 문서
이 가이드에서 사용되는 메서드 또는 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.