Today
Total
KoreanEnglishFrenchGermanJapaneseSpanishChinese (Simplified)
관리 메뉴

DB & AWS Knowledge

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

카테고리 없음

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

`O` 2025. 6. 14. 15:51
728x90
반응형

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

 

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

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

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

 

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

 

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

EC2 Amazon Linux 2023 에 MongoDB 를 설치하는 방법은 아래의 링크를 참조한다.

 

[+] https://www.mongodb.com/ko-kr/docs/manual/tutorial/install-mongodb-on-amazon/#std-label-install-mdb-community-amazon-linux

MongoDB shell 을 통한 MongoDB 접속시 사용하는 기본 명령어

 

- MongoDB 는 아래의 명령어로 기본접속이 가능하다

Mongo host(host명):30000(port, MongoDB 의 기본 port 는 27017 이다.)/test(DB명)

 

 

- 위의 명령어 없이 기본 shell 로만 대화형 인터페이스로만 들어갈수도 있다.

mongo --nodb

 

 

- 위의 상태로만 접속을 해도 shell 에서 아래의과정으로 mongod 에 접속이 가능하다.

> conn = new Mongo("127.0.0.1:27017")
mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000
> db = conn.getDB("test")
test
test>

 

 

- 다른 프로그램과 마찬가지로 MongoDB 도 help 를 사용 할 수 있다.

test> help

  Shell Help:

    log                                        'log.info(<msg>)': Write a custom info/warn/error/fatal/debug message to the log file
                                               'log.getPath()': Gets a path to the current log file

    use                                        Set current database
    show                                       'show databases'/'show dbs': Print a list of all available databases
                                               'show collections'/'show tables': Print a list of all collections for current database
                                               'show profile': Prints system.profile information
                                               'show users': Print a list of all users for current database
                                               'show roles': Print a list of all roles for current database
                                               'show log <type>': log for current connection, if type is not set uses 'global'
                                               'show logs': Print all logs
    exit                                       Quit the MongoDB shell with exit/exit()/.exit
    quit                                       Quit the MongoDB shell with quit/quit()
    Mongo                                      Create a new connection and return the Mongo object. Usage: new Mongo(URI, options [optional])
    connect                                    Create a new connection and return the Database object. Usage: connect(URI, username [optional], password [optional])
    it                                         result of the last line evaluated; use to further iterate
    version                                    Shell version
    load                                       Loads and runs a JavaScript file into the current shell environment
    enableTelemetry                            Enables collection of anonymous usage data to improve the mongosh CLI
    disableTelemetry                           Disables collection of anonymous usage data to improve the mongosh CLI
    passwordPrompt                             Prompts the user for a password
    sleep                                      Sleep for the specified number of milliseconds
    print                                      Prints the contents of an object to the output
    printjson                                  Alias for print()
    convertShardKeyToHashed                    Returns the hashed value for the input using the same hashing function as a hashed index.
    cls                                        Clears the screen like console.clear()
    isInteractive                              Returns whether the shell will enter or has entered interactive mode

  For more information on usage: https://mongodb.com/docs/manual/reference/method

 

 

- 추가로 help 옆에 명령어를 추가로 붙이면, DB 단위, collection 단위로 help 명령어를 확인 할 수 있다.

test> db.help()

  Database Class:

    getMongo                                   Returns the current database connection
    getName                                    Returns the name of the DB
    getCollectionNames                         Returns an array containing the names of all collections in the current database.
    getCollectionInfos                         Returns an array of documents with collection information, i.e. collection name and options, for the current database.
    runCommand                                 Runs an arbitrary command on the database.
    adminCommand                               Runs an arbitrary command against the admin database.
    aggregate                                  Runs a specified admin/diagnostic pipeline which does not require an underlying collection.
    getSiblingDB                               Returns another database without modifying the db variable in the shell environment.
    getCollection                              Returns a collection or a view object that is functionally equivalent to using the db.<collectionName>.
    dropDatabase                               Removes the current database, deleting the associated data files.
    createUser                                 Creates a new user for the database on which the method is run. db.createUser() returns a duplicate user error if the user already exists on the database.
    updateUser                                 Updates the user’s profile on the database on which you run the method. An update to a field completely replaces the previous field’s values. This includes updates to the user’s roles array.
    changeUserPassword                         Updates a user’s password. Run the method in the database where the user is defined, i.e. the database you created the user.
    logout                                     Ends the current authentication session. This function has no effect if the current session is not authenticated.
    dropUser                                   Removes the user from the current database.
    dropAllUsers                               Removes all users from the current database.
    auth                                       Allows a user to authenticate to the database from within the shell.
    grantRolesToUser                           Grants additional roles to a user.
    revokeRolesFromUser                        Removes a one or more roles from a user on the current database.
    getUser                                    Returns user information for a specified user. Run this method on the user’s database. The user must exist on the database on which the method runs.
    getUsers                                   Returns information for all the users in the database.
    createCollection                           Create new collection
    createEncryptedCollection                  Creates a new collection with a list of encrypted fields each with unique and auto-created data encryption keys (DEKs). This is a utility function that internally utilises ClientEnryption.createEncryptedCollection.
    createView                                 Create new view
    createRole                                 Creates a new role.
    updateRole                                 Updates the role’s profile on the database on which you run the method. An update to a field completely replaces the previous field’s values.
    dropRole                                   Removes the role from the current database.
    dropAllRoles                               Removes all roles from the current database.
    grantRolesToRole                           Grants additional roles to a role.
    revokeRolesFromRole                        Removes a one or more roles from a role on the current database.
    grantPrivilegesToRole                      Grants additional privileges to a role.
    revokePrivilegesFromRole                   Removes a one or more privileges from a role on the current database.
(...)

test> db.foo.help()

  Collection Class:

    aggregate                                  Calculates aggregate values for the data in a collection or a view.
    bulkWrite                                  Performs multiple write operations with controls for order of execution.
    count                                      Returns the count of documents that would match a find() query for the collection or view.
    countDocuments                             Returns the count of documents that match the query for a collection or view.
    deleteMany                                 Removes all documents that match the filter from a collection.
    deleteOne                                  Removes a single document from a collection.
    distinct                                   Finds the distinct values for a specified field across a single collection or view and returns the results in an array.
    estimatedDocumentCount                     Returns the count of all documents in a collection or view.
    find                                       Selects documents in a collection or view.
    findAndModify                              Modifies and returns a single document.
    findOne                                    Selects documents in a collection or view.
    renameCollection                           Renames a collection.
    findOneAndDelete                           Deletes a single document based on the filter and sort criteria, returning the deleted document.
    findOneAndReplace                          Modifies and replaces a single document based on the filter and sort criteria.
    findOneAndUpdate                           Updates a single document based on the filter and sort criteria.
    insert                                     Inserts a document or documents into a collection.
    insertMany                                 Inserts multiple documents into a collection.
    insertOne                                  Inserts a document into a collection.
    isCapped                                   Checks if a collection is capped
    remove                                     Removes documents from a collection.
    replaceOne                                 Replaces a single document within the collection based on the filter.
    update                                     Modifies an existing document or documents in a collection.
    updateMany                                 Updates all documents that match the specified filter for a collection.
    updateOne                                  Updates a single document within the collection based on the filter.
    compactStructuredEncryptionData            Compacts structured encryption data
    convertToCapped                            calls {convertToCapped:'coll', size:maxBytes}} command
    createIndexes                              Creates one or more indexes on a collection
    createIndex                                Creates one index on a collection
    ensureIndex                                Creates one index on a collection
    getIndexes                                 Returns an array that holds a list of documents that identify and describe the existing indexes on the collection.
    getIndexSpecs                              Alias for getIndexes. Returns an array that holds a list of documents that identify and describe the existing indexes on the collection.
    getIndices                                 Alias for getIndexes. Returns an array that holds a list of documents that identify and describe the existing indexes on the collection.
    getIndexKeys                               Return an array of key patterns for indexes defined on collection
    dropIndexes                                Drops the specified index or indexes (except the index on the _id field) from a collection.
    dropIndex                                  Drops or removes the specified index from a collection.
    totalIndexSize                             Reports the total size used by the indexes on a collection.
    reIndex                                    Rebuilds all existing indexes on a collection.
    getDB                                      Get current database.
    getMongo                                   Returns the Mongo object.
    dataSize                                   This method provides a wrapper around the size output of the collStats (i.e. db.collection.stats()) command.
    storageSize                                The total amount of storage allocated to this collection for document storage.
    totalSize                                  The total size in bytes of the data in the collection plus the size of every index on the collection.
    drop                                       Removes a collection or view from the database.
    exists                                     Returns collection infos if the collection exists or null otherwise.
    getFullName                                Returns the name of the collection prefixed with the database name.
    getName                                    Returns the name of the collection.
(...)

 

- Javascript file 을 만들어서 sh 명령문에 바로 적용 할 수 있다.

#scrip1.js 파일 생성

print("I am script1.js")

# mongosh 에 바로 수행

$ mongosh script1.js
I am script1.js

 

- 아래와 같이 host,port,db 를 명시하여 적용 할 수 있다.

$ mongosh 127.0.0.1:27017/test script1.js
I am script1.js

 

- Shell 안에서 바로 파일을 load 할 수 있다.

test> load("script1.js")
I am script1.js
true

 

- 스크립트를 만들 때, shell 에서 사용하는 명령어를 Javascript 로 변환 해야 할 수 있다.

예를 들어, show db 는 javascript 파일에서는 db.get.Mongo().getDBs() 로 변환해서 작성해야한다.

 

- Javascript 파일이 위치한 경로와 실제 mongosh 를 수행하는 경로가 다를 시, 절대경로를 입력하면 다른 경로에 있는 Javascript 파일을 load 할 수 있다.

test> load("/home/ec2-user/script1.js")
I am script1.js
true

 

- Linux 등에서 프로그램을 실행 시, 임의로 시작 문구를 만들 수 있는 것 처럼 MongoDB 도 시작 문구를 만들 수 있다.

$ vi .mongoshrc.js

var compliment = ["attractive", "intelligent", "like Batman"];
var index = Math.floor(Math.random()*3);

print("Hello, you're looking particulary "+compliment[index]+" today!");

#작성 후 Mongosh 실행행

$ mongosh
Current Mongosh Log ID: 684d191a3094095ba169e327
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-14T05:33:28.794+00:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
   2025-06-14T05:33:28.794+00:00: For customers running the current memory allocator, we suggest changing the contents of the following sysfsFile
   2025-06-14T05:33:28.794+00:00: For customers running the current memory allocator, we suggest changing the contents of the following sysfsFile
   2025-06-14T05:33:28.794+00:00: We suggest setting the contents of sysfsFile to 0.
   2025-06-14T05:33:28.794+00:00: vm.max_map_count is too low
------

Hello, you're looking particulary attractive today!

 

 

728x90
반응형
Comments