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

MongoDB에서 find()와 pretty()로 다양한 형식의 특정 데이터 조회하는 방법

MongoDB에서 조건에 맞는 특정 데이터를 조회하려면 find() 메서드를 사용하면 됩니다. 조회 결과를 보기 좋게 정렬된 형식으로 출력하고 싶다면 pretty() 메서드를 함께 활용하세요. 이번 글에서는 실제 예제를 통해 중첩된 필드의 데이터를 다양한 형식으로 가져오는 방법을 단계별로 살펴보겠습니다.

1. 샘플 컬렉션 생성하기

먼저 insertOne() 메서드를 사용해 학생 정보가 담긴 문서들을 컬렉션에 삽입합니다. 아래 예제에서는 학생 이름(StudentName)과 함께 부모님 이름(FatherName), 국가(CountryName), 우편번호(ZipCode) 등이 중첩된 객체 구조로 저장되어 있습니다.

> db.getSpecificData.insertOne(
... {
...    "StudentName": "John",
...    "Information": {
...       "FatherName": "Chris",
...       "Place": {
...          "CountryName": "US",
...          "ZipCode":"111344"
...       },
...       "id": "1"
...    }
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e039abdf5e889d7a5199509")
}
> db.getSpecificData.insertOne(
...    {
...       "StudentName": "Carol",
...       "Information": {
...          "FatherName": "Robert",
...          "Place": {
...             "CountryName": "UK",
...             "ZipCode":"746464"
...          },
...          "id": "2"
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e039ae6f5e889d7a519950a")
}
>
> db.getSpecificData.insertOne(
... {
...    "StudentName": "David",
...    "Information": {
...       "FatherName": "Carol",
...       "Place": {
...          "CountryName": "US",
...          "ZipCode":"567334"
...       },
...    "id": "3"
...    }
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e039ae7f5e889d7a519950b")
}
>
> db.getSpecificData.insertOne(
...    {
...       "StudentName": "Jace",
...       "Information": {
...          "FatherName": "Bob",
...          "Place": {
...             "CountryName": "US",
...             "ZipCode":"999999"
...          },
...          "id": "4"
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e039ae8f5e889d7a519950c")
}

2. find() 메서드로 문서 조회하기

find() 메서드의 첫 번째 인자에는 조회 조건을 담은 쿼리를 전달합니다. 아래 쿼리는 'Information.Place.CountryName' 값이 "US"인 문서만 필터링하여 보여줍니다. 이처럼 점(.) 표기법을 사용하면 중첩된 하위 필드에도 손쉽게 접근할 수 있습니다.

> db.getSpecificData.find({'Information.Place.CountryName':"US"}, {}, {limit: 2}, function(error, data) {}).pretty();

위 쿼리를 실행하면 다음과 같이 pretty() 덕분에 들여쓰기가 적용된 가독성 높은 형태로 결과가 출력됩니다.

{
   "_id" : ObjectId("5e039abdf5e889d7a5199509"),
   "StudentName" : "John",
   "Information" : {
      "FatherName" : "Chris",
      "Place" : {
         "CountryName" : "US",
         "ZipCode" : "111344"
      },
   "id" : "1"
   }
}
{
   "_id" : ObjectId("5e039ae7f5e889d7a519950b"),
   "StudentName" : "David",
   "Information" : {
      "FatherName" : "Carol",
      "Place" : {
         "CountryName" : "US",
         "ZipCode" : "567334"
      },
      "id" : "3"
   }
}
{
   "_id" : ObjectId("5e039ae8f5e889d7a519950c"),
   "StudentName" : "Jace",
   "Information" : {
      "FatherName" : "Bob",
      "Place" : {
         "CountryName" : "US",
         "ZipCode" : "999999"
      },
      "id" : "4"
   }
}

3. 다른 형식으로 특정 데이터 가져오기

몽고 셸(mongo shell)에서는 limit 옵션을 별도 인자로 전달하는 것보다 limit() 메서드를 체이닝(chain)하는 방식이 일반적입니다. limit(2)를 붙이면 조건에 맞는 문서 중 최대 2개만 반환되도록 결과 개수를 제한할 수 있습니다.

> db.getSpecificData.find({'Information.Place.CountryName':"US"}, {}).limit(2);

실행 결과는 다음과 같습니다. pretty() 없이 실행했기 때문에 각 문서가 한 줄로 간결하게 출력됩니다.

{ "_id" : ObjectId("5e039abdf5e889d7a5199509"), "StudentName" : "John", "Information" : { "FatherName" : "Chris", "Place" : { "CountryName" : "US", "ZipCode" : "111344" }, "id" : "1" } }
{ "_id" : ObjectId("5e039ae7f5e889d7a519950b"), "StudentName" : "David", "Information" : { "FatherName" : "Carol", "Place" : { "CountryName" : "US", "ZipCode" : "567334" }, "id" : "3" } }

핵심 정리


- find(): 조건에 맞는 문서를 조회하는 기본 메서드입니다.
- pretty(): 조회 결과를 들여쓰기된 JSON 형식으로 보기 좋게 출력합니다.
- limit(): 반환되는 문서의 개수를 제한합니다.
- 점 표기법: 'Information.Place.CountryName'처럼 중첩된 필드에도 직접 조건을 걸 수 있습니다.

이 세 가지 메서드와 점 표기법만 익혀두면 MongoDB에서 원하는 데이터를 원하는 형식으로 자유롭게 조회할 수 있습니다.