다음 옵션을 사용하여 MongoDB Shell의 다양한 측면을 보고 제어합니다.
일반 옵션
--build-infoJSON 형식의 문서와
mongosh빌드 및 드라이버 종속성에 대한 정보를 반환합니다.예시: 빌드 정보 보기
터미널에서 다음 명령을 실행하여
mongosh바이너리의 빌드 정보 및 드라이버 종속성을 확인할 수 있습니다:mongosh --build-info 이 명령은 다음과 같은 JSON 형식의 문서를 반환합니다.
{ version: '1.10.1', distributionKind: 'packaged', buildArch: 'x64', buildPlatform: 'linux', buildTarget: 'unknown', buildTime: '2023-06-21T09:49:37.225Z', gitVersion: '05ad91b4dd40382a13f27abe1ae8c3f9f52a38f7', nodeVersion: 'v16.20.1', opensslVersion: '3.1.1', sharedOpenssl: true, runtimeArch: 'x64', runtimePlatform: 'darwin', deps: { nodeDriverVersion: '5.6.0' } }
--eval <javascript>JavaScript 표현식을 평가합니다. 단일
--eval인수를 사용하거나 여러 개의--eval인수를 함께 사용할 수 있습니다.mongosh는 인수를 평가한 후--eval결과를 명령줄에 인쇄합니다.--eval성명서를 여러 개 사용하는 경우mongosh는 마지막--eval결과만 인쇄합니다.You can use the
--jsonflag with--evalto returnmongoshresults in Extended JSON format.mongoshsupports both--json=canonicaland--json=relaxedmodes. If you omit the mode,mongoshdefaults to thecanonicalmode. The--jsonflag is mutually exclusive with--shell.예시: 형식 출력
자동 구문 분석에 적합한 출력을 얻으려면
EJSON.stringify()를 사용합니다.mongosh --quiet --host rs0/centos1104 --port 27500 \ --eval "EJSON.stringify(rs.status().members.map( \ m => ({'id':m._id, 'name':m.name, 'stateStr':m.stateStr})));" \ | jq jq로 구문 분석을 수행하면 다음과 같은 결과가 표시됩니다.[ { "id": 0, "name": "centos1104:27500", "stateStr": "PRIMARY" }, { "id": 1, "name": "centos1104:27502", "stateStr": "SECONDARY" }, { "id": 2, "name": "centos1104:27503", "stateStr": "SECONDARY" } ] 참고
EJSON에는 서식 지정 옵션이 내장되어jq와 같은 구문 분석기가 필요하지 않을 수 있습니다. 예를 들어, 다음 코드는 위와 동일한 형식의 결과를 생성합니다.mongosh --quiet --host rs0/centos1104 --port 27500 \ --eval "EJSON.stringify( rs.status().members.map( \ ({ _id, name, stateStr }) => ({ _id, name, stateStr })), null, 2);" 예: 다중 --eval 인수
moviesDatabase에서 컬렉션 목록을 확보하려면 여러--eval성명서를 사용합니다.mongosh --quiet \ --eval 'use moviesDatabase' \ --eval 'show collections' \ mongodb://localhost/ 예: --json 옵션
여러
--eval문을 사용하여 확장 JSON 형식으로 컬렉션의 통계를 반환하려면 다음을 수행합니다.mongosh --quiet --json=relaxed \ --eval 'use <database-name>' \ --eval 'db.<collection>.stats()' \ mongodb://localhost/
--file, -f <javascript>MongoDB Shell 콘솔에 들어가지 않고 명령줄에서 스크립트를 실행합니다.
자세한 내용과 예제는 명령줄에서 스크립트 실행을 참조합니다.
--no-quietDisables the default
--quietoption mode for non-interactive shell sessions. When specified,mongoshdisplays all messages during startup.
--norc시작 시 셸의
~/.mongoshrc.js소싱 및 평가를 방지합니다.--norcalso prevents the shell from loading any snippets you installed with thesnippet installcommand. Instead, you can load snippets with thesnippet load-allcommand. See Snippet Commands for more information.
--quiet시작할 때 모든 메시지(예: 환영 메시지 및 시작 경고)를 건너뛰고 프롬프트로 바로 이동합니다.
For non-interactive shell sessions, MongoDB enables
--quietby default. You can disable this behavior using--no-quiet.
--skipStartupWarningsPrevents
mongoshfrom displaying server startup warnings when creating a session. To suppress all startup messages, use the--quietoption.
--shellEnables the shell interface. If you invoke the
mongoshcommand and specify a JavaScript file as an argument, or use--evalto specify JavaScript on the command line, the--shelloption provides the user with a shell prompt after the file finishes executing. The--shellflag is mutually exclusive with--json.
Stable API 옵션
--apiVersion <version number>Specifies the apiVersion.
"1"is currently the only supported value.
--apiStrict애플리케이션이 Stable API 외부의 명령이나 동작을 사용하는 경우 서버가 APIStrictError 로 응답하도록 지정합니다.
If you specify
--apiStrict, you must also specify--apiVersion.
--apiDeprecationErrorsSpecifies that the server will respond with APIDeprecationError if your application uses a command or behavior that is deprecated in the specified
apiVersion.If you specify
--apiDeprecationErrors, you must also specify--apiVersion.
연결 옵션
--host <hostname>Specifies the name of the host machine where the
mongodormongosis running. If this is not specified, the MongoDB Shell attempts to connect to a MongoDB process running on the localhost.- 다음을 수행하여 복제본 세트에 연결합니다.
Specify the
replica set nameand a seed list of set members. Use the following form:<replSetName>/<hostname1><:port>,<hostname2><:port>,<...> - For TLS/SSL connections (
--tls), - The MongoDB Shell verifies that the hostname (specified in the
--hostoption or the connection string) matches theSAN(or, ifSANis not present, theCN) in the certificate presented by themongodormongos. IfSANis present, the MongoDB Shell does not match against theCN. If the hostname does not match theSAN(orCN), the MongoDB Shell shell fails to connect.
- DNS 시드 목록 연결의 경우,
Specify the connection protocol as
mongodb+srv, followed by the DNS SRV hostname record and any options. TheauthSourceandreplicaSetoptions, if included in the connection string, overrides any corresponding DNS-configured options set in the TXT record. Use of themongodb+srv:connection string implicitly enables TLS (normally set withtls=true) for the client connection. The TLS option can be turned off by settingtls=falsein the query string.예시
mongodb+srv://server.example.com/?connectionTimeoutMS=3000
--port <port>Specifies the port where the
mongodormongosinstance is listening. If--portis not specified, the MongoDB Shell attempts to connect to port27017.
TLS 옵션
--tlsEnables connection to a
mongodormongosthat has TLS support enabled.TLS/SSL 및 MongoDB에 대해 자세히 알아보려면 다음을 참조하세요.
--tlsCertificateKeyFile <filename>Specifies the
.pemfile that contains both the TLS certificate and key formongosh. Specify the file name of the.pemfile using relative or absolute paths.This option is required when using the
--tlsoption to connect to amongodormongosinstance that requires client certificates. That is, the MongoDB Shell presents this certificate to the server.참고
TLS/SSL 및 MongoDB에 대해 자세히 알아보려면 다음을 참조하세요.
--tlsCertificateKeyFilePassword <value>Specifies the password to de-crypt the certificate-key file (i.e.
--tlsCertificateKeyFile).인증서 키 파일이 암호화된 경우에만
--tlsCertificateKeyFilePassword옵션을 사용합니다. MongoDB Shell은 언제나 모든 기록 및 보고 결과에서 암호를 삭제합니다.If the private key in the PEM file is encrypted and you do not specify the
--tlsCertificateKeyFilePasswordoption; the MongoDB Shell prompts for a passphrase.TLS/SSL 인증서 암호를 참조하세요.
TLS/SSL 및 MongoDB에 대해 자세히 알아보려면 다음을 참조하세요.
--tlsCAFile <filename>Specifies the
.pemfile that contains the root certificate chain from the Certificate Authority. This file is used to validate the certificate presented by themongod/mongosinstance.상대 경로 또는 절대 경로를 사용해
.pem파일의 이름을 지정합니다.TLS/SSL 및 MongoDB에 대해 자세히 알아보려면 다음을 참조하세요.
--tlsCRLFile <filename>인증서 해지 목록이 포함된
.pem파일을 지정합니다. 상대 경로 또는 절대 경로를.pem파일의 이름을 지정합니다.TLS/SSL 및 MongoDB에 대해 자세히 알아보려면 다음을 참조하세요.
--tlsAllowInvalidHostnamesDisables the validation of the hostnames in the certificate presented by the
mongod/mongosinstance. Allows the MongoDB Shell to connect to MongoDB instances even if the hostname in the server certificates do not match the server's host.TLS/SSL 및 MongoDB에 대해 자세히 알아보려면 다음을 참조하세요.
--tlsAllowInvalidCertificates버전 4.2에 추가 되었습니다.
Bypasses the validation checks for the certificates presented by the
mongod/mongosinstance and allows connections to servers that present invalid certificates.참고
MongoDB 4.0부터 x.509 인증 사용할 때
--tlsAllowInvalidCertificates를 지정하면 유효하지 않은 인증서는 TLS 연결을 설정하는 데에는 충분하지만, 인증 에는 충분하지 않습니다.경고
Although available, avoid using the
--tlsAllowInvalidCertificatesoption if possible. If the use of--tlsAllowInvalidCertificatesis necessary, only use the option on systems where intrusion is not possible.If the MongoDB Shell shell (and other Connect to a TLS-Enabled Replica Set) runs with the
--tlsAllowInvalidCertificatesoption, the shell (and other Connect to a TLS-Enabled Replica Set) do not attempt to validate the server certificates. This creates a vulnerability to expiredmongodandmongoscertificates as well as to foreign processes posing as validmongodormongosinstances. If you only need to disable the validation of the hostname in the TLS certificates, see--tlsAllowInvalidHostnames.TLS/SSL 및 MongoDB에 대해 자세히 알아보려면 다음을 참조하세요.
--tlsCertificateSelector <parameter>=<value>Available on Windows and macOS as an alternative to
--tlsCertificateKeyFile.중요
Windows 및 개인 키 가져오기
개인 키를 가져올 때는 내보내기 가능으로 표시해야 합니다. Windows 인증서 가져오기 마법사는 이 옵션을 기본으로 선택하지 않습니다.

The
--tlsCertificateKeyFileand--tlsCertificateSelectoroptions are mutually exclusive. You can only specify one.운영 체제의 인증서 저장소에서 일치하는 인증서를 선택하기 위해 인증서 속성을 지정합니다.
--tlsCertificateSelectoraccepts an argument of the format<property>=<value>where the property can be one of the following:속성값 유형설명subjectASCII 문자열
인증서의 주체 이름 또는 일반 이름
thumbprint16진수 문자열
16진수로 표현되는 일련의 바이트로, SHA-1 다이제스트로 공개 키를 식별하는 데 사용됩니다.
thumbprint을(를)fingerprint(이)라고 부르기도 합니다.시스템 SSL 인증서 저장소를 사용할 때 온라인 인증서 상태 프로토콜(OCSP)을 사용해 인증서의 해지 상태를 확인할 수 있습니다.
--tlsDisabledProtocols <string>지정된 TLS 프로토콜을 비활성화합니다. 이 옵션은 다음 프로토콜을 인식합니다.
TLS1_0TLS1_1TLS1_2(버전 4.0.4, 3.6.9, 3.4.24부터)
TLS1_3macOS에서는
TLS1_1은 비활성화하고TLS1_0와TLS1_2가 모두 활성화된 상태를 유지할 수 없습니다. 예를 들어,TLS1_0,TLS1_1처럼 다른 2개의 프로토콜 중 하나 이상을 비활성화해야 합니다.여러 프로토콜을 나열하려면 쉼표로 구분된 프로토콜 목록으로 지정합니다( 예시:
TLS1_0,TLS1_1).지정된 비활성화 프로토콜은 기본으로 설정된 비활성화 프로토콜을 덮어씁니다.
버전 4.0 부터 MongoDB 시스템에서 TLS 1.0 1.1+를 사용할 수 있는 경우 TLS 사용을 비활성화합니다. 비활성화된 TLS 을 활성화 1.0 하려면
none을(를)(으)로--tlsDisabledProtocols지정합니다.
--tlsUseSystemCAAllows
mongoshto load TLS certificates already available to the operating system's certificate authority without explicitly specifying the certificates to the shell. You cannot turn off this behavior.--tlsUseSystemCAcan still be set for backward compatibility, but it has no effect.참고
이 플래그는 MongoDB 연결과 OIDC 자격 증명 공급자 연결 모두에 적용됩니다.
인증 옵션
--authenticationDatabase <dbname>Specifies the authentication database where the specified
--usernamehas been created. See Authentication Database.If you do not specify a value for
--authenticationDatabase, the MongoDB Shell uses the database specified in the connection string.
--authenticationMechanism <name>MongoDB Shell
mongod또는mongos에 인증하는 데 사용하는 인증 메커니즘 을 지정합니다.authenticationMechanism을(를) 지정하지 않고 사용자 자격 증명 제공하는 경우, MongoDB Shell 및 드라이버는 SCRAM-SHA-256 사용을 시도합니다. 이 작업이 실패하면 SCRAM-SHA-1로 돌아갑니다.값설명RFC 5802 standard Salted Challenge Response Authentication Mechanism using the SHA-1 hash function.
RFC 7677 standard Salted Challenge Response Authentication Mechanism using the SHA-256 hash function.
featureCompatibilityVersion이
4.0으로 설정되어야 합니다.MongoDB TLS certificate authentication.
GSSAPI (Kerberos)
Kerberos를 사용한 외부 인증. 이 메커니즘은 MongoDB Enterprise에서만 사용할 수 있습니다.
PLAIN (LDAP SASL)
LDAP 사용한 외부 인증 .
PLAIN을(를) 사용하여 데이터베이스 내 사용자를 인증할 수도 있습니다.PLAIN은(는) 비밀번호를 일반 텍스트로 전송합니다. 이 메커니즘은 MongoDB 엔터프라이즈 및 MongoDB Atlas 에서 사용할 수 있습니다.MONGODB-OIDC (OpenID Connect)
OpenID Connect를 사용한 외부 인증 . 이 메커니즘은 MongoDB 엔터프라이즈 및 MongoDB Atlas 에서 사용할 수 있습니다.
MONGODB-AWS(Amazon Web Services IAM)Amazon Web Services Identity and Access Management(Amazon Web Services IAM) 자격 증명 사용한 외부 인증 . 이 메커니즘은 MongoDB 엔터프라이즈 및 MongoDB Atlas 에서 사용할 수 있습니다.
--gssapiServiceNameSpecify the name of the service using GSSAPI/Kerberos. Only required if the service does not use the default name of
mongodb.이 옵션은 MongoDB Enterprise에서만 사용할 수 있습니다.
--sspiHostnameCanonicalization <string>호스트 이름 표준화 사용 여부를 지정합니다.
--sspiHostnameCanonicalizationhas the same effect as setting theCANONICALIZE_HOST_NAME:true|falsekey-pair in theauthMechanismPropertiesportion of the connection string.If
--sspiHostnameCanonicalizationis set to:forwardAndReverse정방향 DNS 조회를 수행한 다음 역방향 조회를 수행합니다.mongosh1.3.0에 추가되었습니다.forwardauthMechanismProperties=CANONICALIZE_HOST_NAME:true설정과 효과가 동일합니다.noneauthMechanismProperties=CANONICALIZE_HOST_NAME:false설정과 효과가 동일합니다.
--oidcFlowsOpenID Connect 흐름을 쉼표로 구분된 목록으로 지정합니다. OpenID Connect 흐름은 인증 프로세스를 위해
mongosh가 멱등과 상호 작용하는 방법을 지정합니다.mongosh는 다음 OpenID Connect 흐름을 지원합니다.OpenID 연결 흐름설명auth-code기본값.
mongosh를 클릭하면 브라우저가 열리고 멱등 로그인 화면으로 리디렉션됩니다.device-authmongosh는 인증을 완료하기 위한 URL과 코드를 제공합니다. 이는 보안성이 낮은 OpenID Connect 흐름으로 간주되지만mongosh가 브라우저를 열 수 없는 환경에서 실행될 때 사용할 수 있습니다device-auth를auth-code의 대체 옵션으로 설정하는 방법은 다음 예시에서 확인 가능합니다.mongosh 'mongodb://localhost/' --authenticationMechanism MONGODB-OIDC --oidcFlows=auth-code,device-auth
--oidcDumpTokensmongosh가 예비 디버깅 정보가 포함된 토큰을 출력할지 여부를 지정합니다. 이 옵션은 디버깅 용도로만 사용합니다.--oidcDumpTokens옵션은 다음과 같은 값을 허용합니다.값설명redacted--oidcDumpTokens만 설정할 때 기본값입니다. 민감한 정보가 삭제된 상태로 토큰 디버깅 정보를 출력합니다.include-secrets데이터베이스 서버에 인증할 수 있는 자격 증명을 포함하여 토큰 디버깅 정보를 출력합니다.
중요
include-secrets값은 공격자가 인증에 사용할 수 있는 자격 증명을 노출합니다. 권한이 없는 사람이mongosh의 출력을 볼 수 없고 진단 목적으로 자격 증명이 필요한 경우에만 이 옵션을 사용하세요.
--oidcIdTokenAsAccessTokenmongosh가 자격 증명 공급자로부터 받은 ID 토큰을 액세스 토큰 대신 사용하는지 여부를 지정합니다. JWT 액세스 토큰을 제공하도록 구성할 수 없는 자격 증명 공급자와 함께 이 옵션을 사용합니다.
--oidcNoNonce기본값으로
mongosh은 OIDC 권한 부여 코드 흐름 중에 논스 매개 변수를 전송합니다.--oidcNoNonce옵션을 설정하다 하면mongosh은 논스 매개변수를 전송하지 않습니다. 자격 증명 공급자 가 권한 부여 의 일부로 논스 값을 지원 하지 않는 경우 이 옵션을 사용합니다.
--oidcRedirectUri인증 후 멱등이 사용자를 리디렉션할 URI를 지정합니다. URI는 멱등의 구성과 일치해야 합니다. 기본값은
http://localhost:27097/redirect입니다.
--oidcTrustedEndpoint현재 연결이 Atlas 또는
localhost이(가) 아닌 신뢰할 수 있는 엔드포인트에 있음을 나타냅니다. 이렇게 하면 액세스 토큰이 서버 로 전송됩니다. 신뢰할 수 있는 서버에 연결할 때만 이 옵션을 사용합니다.
--browserMONGODB-OIDC가 활성화된 경우mongosh가 리디렉션하는 브라우저를 지정합니다.이 옵션은 시스템 셸에서 실행됩니다.
브라우저 열기를 완전히 비활성화하려면
--no-browser를 설정합니다.
--password <password>, -p <password>Specifies a password with which to authenticate to a MongoDB database that uses authentication. Use in conjunction with the
--usernameand--authenticationDatabaseoptions.To force the MongoDB Shell to prompt for a password, enter the
--passwordoption as the last option and leave out the argument.
--username <username>, -u <username>Specifies a username with which to authenticate to a MongoDB database that uses authentication. Use in conjunction with the
--passwordand--authenticationDatabaseoptions.
세션 옵션
--retryWrites재시도 가능 쓰기를 활성화합니다.
기본적으로 재시도 가능한 쓰기는 다음과 같습니다.
활성화됨
mongosh레거시
mongo셸에서 비활성화됨
To disable retryable writes, use
--retryWrites=false.세션 정보는 클라이언트 세션 및 인과적 일관성 보장에서 확인하세요.
필드 레벨 암호화 옵션
--cryptSharedLibPath <string>버전 8.2에 추가 되었습니다.
자동 암호화 공유 라이브러리의 경로입니다. 라이브러리는 8 2버전이.. 이상이어야 합니다.0
mongosh셸 세션에 자동 암호화 사용하는 데 필요합니다.
--awsAccessKeyId <string>An AWS Access Key associated with an IAM user who has
ListandReadpermissions for the AWS Key Management Service (KMS).mongoshuses the specified--awsAccessKeyIdto access the KMS.--awsAccessKeyIdis required to enable Client-Side Field Level Encryption for themongoshshell session.--awsAccessKeyIdrequires both of the following command line options:If
--awsAccessKeyIdis omitted, use theMongo()constructor within the shell session to enable client-side field level encryption.To mitigate the risk of leaking access keys into logs, consider specifying an environmental variable to
--awsAccessKeyId.
--awsSecretAccessKey <string>An AWS Secret Key associated to the specified
--awsAccessKeyId.--awsSecretAccessKeyis required to enable Client-Side Field Level Encryption for themongoshsession.--awsSecretAccessKeyrequires both of the following command line options:If
--awsSecretAccessKeyand its supporting options are omitted, useMongo()within the shell session to enable client-side field level encryption.To mitigate the risk of leaking access keys into logs, consider specifying an environmental variable to
--awsSecretAccessKey.
--awsSessionToken <string>An AWS Session Token associated to the specified
--awsAccessKeyId.--awsSessionTokenis required to enable Client-Side Field Level Encryption for themongoshshell session.--awsSessionTokenrequires all of the following command line options:If
--awsSessionTokenand its supporting options are omitted, useMongo()within the shell session to enable client-side field level encryption.To mitigate the risk of leaking access keys into logs, consider specifying an environmental variable to
--awsSessionToken.
--keyVaultNamespace <string>The full namespace (
<database>.<collection>) of the collection used as a key vault for Client-Side Field Level Encryption.--keyVaultNamespaceis required for enabling client-side field level encryption for themongoshshell session.mongoshcreates the specified namespace if it does not exist.--keyVaultNamespacerequires both of the following command line options:If
--keyVaultNamespaceand its supporting options are omitted, use theMongo()constructor within the shell session to enable client-side field level encryption.