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

MongoDB 명령줄로 컬렉션(테이블)에 연결하고 데이터를 조회하는 방법

MongoDB는 관계형 데이터베이스의 '테이블'과 달리 컬렉션(Collection)이라는 개념을 사용합니다. 따라서 명령줄(mongo 셸)에서 특정 테이블, 즉 컬렉션에 접근하려면 db 명령어를 활용해야 합니다.

기본 문법

컬렉션에 연결하여 데이터를 조회하는 기본적인 방법은 다음과 같습니다.

db.yourCollectionName.find();

find() 메서드는 해당 컬렉션의 모든 문서를 반환합니다. 이제 실제 예제를 통해 단계별로 살펴보겠습니다.

1단계: 데이터베이스 선택 및 확인

예제에서는 여러 컬렉션을 포함하고 있는 "sample" 데이터베이스를 사용합니다. 먼저 use 명령으로 해당 데이터베이스로 전환합니다.

> use sample;
switched to db sample
> db;
sample

db 명령을 입력하면 현재 작업 중인 데이터베이스가 출력되는 것을 확인할 수 있습니다.

2단계: 컬렉션 목록 확인

데이터베이스에 어떤 컬렉션이 있는지 확인하려면 show collections 명령을 사용합니다.

> show collections;

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

arraySizeErrorDemo
basicInformationDemo
copyThisCollectionToSampleDatabaseDemo
deleteAllRecordsDemo
deleteDocuments
deleteDocumentsDemo
deleteSomeInformation
documentWithAParticularFieldValueDemo
employee
findListOfIdsDemo
findSubstring
getAllRecordsFromSourceCollectionDemo
getElementWithMaxIdDemo
internalArraySizeDemo
largestDocumentDemo
makingStudentInformationClone
oppositeAddToSetDemo
prettyDemo
returnOnlyUniqueValuesDemo
selectWhereInDemo
sourceCollection
studentInformation
sumOfValueDemo
sumTwoFieldsDemo
truncateDemo
updateInformation
userInformation

3단계: db 명령으로 컬렉션 조회

이제 테이블, 즉 컬렉션에 올바르게 연결하는 방법을 알아보겠습니다. 핵심은 db 명령 뒤에 컬렉션 이름을 붙여주는 것입니다. 예를 들어 userInformation 컬렉션의 모든 문서를 조회하는 쿼리는 다음과 같습니다.

> db.userInformation.find();

실행 결과는 아래와 같이 JSON 형태의 문서가 출력됩니다.

{ "_id" : ObjectId("5c6a765964f3d70fcc9147f5"), "Name" : "John", "Age" : 30, "isStudent" : false, "Subjects" : [ "Introduction to java", "Introduction to MongoDB" ] }

추가 팁: 가독성 좋게 출력하기

조회 결과가 길거나 복잡한 경우 pretty() 메서드를 함께 사용하면 들여쓰기가 적용된 보기 편한 형태로 출력됩니다.

> db.userInformation.find().pretty();

이처럼 MongoDB에서는 use로 데이터베이스를 선택한 후, db.컬렉션명.find() 구문만 기억하면 명령줄에서 손쉽게 원하는 컬렉션에 연결하고 데이터를 조회할 수 있습니다.