Today
Total
KoreanEnglishFrenchGermanJapaneseSpanishChinese (Simplified)
관리 메뉴

DB & AWS Knowledge

MongoDB shell 사용방법 및 관련 명령어 - 2 본문

MongoDB, AWS DocumentDB/아키텍처 및 내부 구조

MongoDB shell 사용방법 및 관련 명령어 - 2

`O` 2025. 6. 17. 02:12
728x90
반응형

이 페이지에서는 이전 게시글에 이어 MongoDB 를 사용하기 위해 필요한 MongoDB shell 사용방법 및 관련 명령어에 대하여 다룬

다.

 

[+] 2025.06.14 - [분류 전체보기] - MongoDB shell 사용방법 및 관련 명령어 - 1

 

또한, 이 게시글은 도서 O'REILLY 사의 저서 '몽고DB 완벽가이드' 의 내용들을 심화 이해하기 위하여 작성하는 글이다.

이 페이지는 perplexity 를 통해 필자가 어떤 prompt 를 작성하여 공부하는지를 공유한다. ([] 로 표기)

또한, 검색이외에 추가로 덧붙일 내용은 ※ 로 추가한다.

 

AI 를 통해 관련된 자료를 검색하다보면 이전 게시글과 중복된 사항도 있으나 이는 복습 및 상기 차원에서 그대로 기재 되도록 한다.

 

마지막으로 이 페이지는 EC2 Amazon Linux 2023 에 설치된 기본 MongoDB 를 사용한다.

 

Mongoshrc.js 파일을 이용한 MongoDB 접속시 표기되는 프롬프트 커스토마이징

 

MongoDB 는 mongoshrc.js 를 이용하여 아래 예시와 같이 mongoshell 의 프롬프트 환경또한 커스토마이징 할 수 있다.

 

#아래의 구문을 추가하여 mongosh 의 prompt 에서 현재 명령어가 수행되는 시간을 표기

$vi ~/.mongoshrc.js

prompt = function() {
        return (new Date())+"> ";
};

$ mongosh 127.0.0.1:27017
Current Mongosh Log ID: 685046103fe32ebbe069e327
Connecting to:          mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.5.2
Using MongoDB:          8.0.10
Using Mongosh:          2.5.2

For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/

------
   The server generated these startup warnings when booting
   2025-06-16T14:19:15.343+00:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
   2025-06-16T14:19:15.344+00:00: For customers running the current memory allocator, we suggest changing the contents of the following sysfsFile
   2025-06-16T14:19:15.344+00:00: For customers running the current memory allocator, we suggest changing the contents of the following sysfsFile
   2025-06-16T14:19:15.344+00:00: We suggest setting the contents of sysfsFile to 0.
   2025-06-16T14:19:15.344+00:00: vm.max_map_count is too low
------

Hello, you're looking particulary intelligent today!
Mon Jun 16 2025 16:28:00 GMT+0000 (Coordinated Universal Time)>

 

Shell 에서 다중 코드 및 객체 블록등을 작성할 때, 아래 줄을 작성 중, 윗줄에서 오타등을 수정하는 건 매우 번거롭다. 이 때 사용할 수 있는데 editor 다. editor 는 아래와 같은 순서로 사용한다.

 

# Mongo shell 사용

# 어떤 editor 를 사용할 지 설정

test> config.set("editor", "vi")

# Editor 가 저장될 경로 설정

test> EDITOR="/home/ec2-user/"
/home/ec2-user/

# 특정 변수를 설정

test> var wap = db.books.findOne({title: "War and Peace"});

# 해당 변수값을 editor 에서 편집

test> edit wap
Opening an editor...

# vi 편집기에서 나오면 해당 변수 값이 shell 에 재반영 된다.

test> wap = null

 

특정 커맨드창에서 version 등의 단어들은 명령어 수행과 연관된 경우 예약어인 경우가 많다. MongoDB 에서 또한 이를 고려해야하는데 이는 사용자가 version 이라는 collection 을 만들면 아래의 기존 예약어와 충돌이 발생할수 있기 때문이다. 이때는 MongoDB 의 함수를 사용해야한다. (아래 예시이외에 여러 함수들은 AI 검색을 사용하면 편리하다.)

 

# version 이라는 collection 에 접근시, 이는 기존 예약어와 충돌된다.

test> db.version
[Function: version] AsyncFunction {
  apiVersions: [ 0, 0 ],
  returnsPromise: true,
  serverVersions: [ '0.0.0', '999.999.999' ],
  topologies: [ 'ReplSet', 'Sharded', 'LoadBalanced', 'Standalone' ],
  returnType: { type: 'unknown', attributes: {} },
  deprecated: false,
  platforms: [ 'Compass', 'Browser', 'CLI' ],
  isDirectShellCommand: false,
  acceptsRawInput: false,
  shellCommandCompleter: undefined,
  help: [Function (anonymous)] Help
}

# getCollection 이라는 함수를 통해 version collection 에 접근

test> db.getCollection("version");
test.version

 

Array (배열) 를 통해 유효하지 않은 collection 명을 피할 수도 있다. 또한 Mongo shell 은 Javascript 편집기 기능도 있으므로, 이를 이용해 아래의 반복문을 통해 Array 에 있는 collection 만 조회 할 수도 있다.

 

test> var collections = ["posts","comments","authors"]

test> for (var i in collections) {
... print(db.blog[collections[i]]);
... }
test.blog.posts
test.blog.comments
test.blog.authors

 

접근하려는 collection 의 이름이 조회하기 힘든 명칭일 시, 아래와 같은 wildcard 등을 이용한 검색을 이용 할 수도 있다.

test> var name = "@#&!"

test> db[name].find()
728x90
반응형
Comments