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

MongoDB에서 하위 데이터(내부 문서)에 접근하고 특정 문서만 조회하는 방법

MongoDB에서 중첩된 하위 데이터(subdata)에 접근하려면 점 표기법(dot notation)을 사용해 키 경로를 지정해야 합니다. 이 글에서는 실제 예제를 통해 컬렉션을 생성하고, 내부에 중첩된 필드 값을 기준으로 특정 문서를 조회하는 방법을 단계별로 살펴보겠습니다.

1. 샘플 컬렉션 생성하기

먼저 학생 정보가 중첩 구조로 저장된 컬렉션을 만들어 보겠습니다. insertOne() 메서드를 사용해 문서를 하나씩 삽입합니다.

> db.demo450.insertOne({"Information":{"StudentDetails":{"StudentName":"Chris","StudentAge":21}}});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7b590e71f552a0ebb0a6e6")
}
> db.demo450.insertOne({"Information":{"StudentDetails":{"StudentName":"David","StudentAge":23}}});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7b591a71f552a0ebb0a6e7")
}
> db.demo450.insertOne({"Information":{"StudentDetails":{"StudentName":"Mike","StudentAge":22}}});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7b592271f552a0ebb0a6e8")
}

각 문서는 InformationStudentDetailsStudentName, StudentAge 형태로 세 단계 깊이의 중첩 구조를 가지고 있습니다.

2. 전체 문서 확인하기

find() 메서드를 사용하면 컬렉션의 모든 문서를 조회할 수 있습니다.

> db.demo450.find();

실행 결과는 다음과 같습니다.

{ "_id" : ObjectId("5e7b590e71f552a0ebb0a6e6"), "Information" : { "StudentDetails" : {
"StudentName" : "Chris", "StudentAge" : 21 } } }
{ "_id" : ObjectId("5e7b591a71f552a0ebb0a6e7"), "Information" : { "StudentDetails" : {
"StudentName" : "David", "StudentAge" : 23 } } }
{ "_id" : ObjectId("5e7b592271f552a0ebb0a6e8"), "Information" : { "StudentDetails" : {
"StudentName" : "Mike", "StudentAge" : 22 } } }

3. 점 표기법으로 하위 데이터 조회하기

중첩된 하위 데이터에 접근하려면 각 필드 이름을 마침표(.)로 연결한 경로를 쿼리 조건에 사용합니다. 아래는 Information.StudentDetails.StudentName 값이 "David"인 문서만 조회하는 쿼리입니다.

> db.demo450.find({"Information.StudentDetails.StudentName":"David"});

실행 결과는 다음과 같습니다.

{ "_id" : ObjectId("5e7b591a71f552a0ebb0a6e7"), "Information" : { "StudentDetails" : {
"StudentName" : "David", "StudentAge" : 23 } } }

정리

MongoDB에서 중첩 문서의 특정 필드를 조건으로 검색할 때는 반드시 전체 키 경로를 따옴표로 감싸 점 표기법으로 작성해야 합니다. 위 예제처럼 {"상위필드.중간필드.하위필드": 값} 형식을 사용하면 원하는 깊이의 데이터에 정확하게 접근할 수 있으며, 이는 배열 요소나 더 깊은 중첩 구조에도 동일하게 적용됩니다.