Docs Menu

콜모드

collMod

collMod makes it possible to add options to a collection or to modify view definitions.

mongosh에서 이 명령은 hideIndex()unhideIndex() 헬퍼 메서드를 통해서도 실행할 수 있습니다.

헬퍼 메서드는 mongosh 사용자에게 편리하지만 데이터베이스 명령과 동일한 수준의 정보를 반환하지 못할 수 있습니다. 편의가 필요하지 않거나 추가 리턴 필드가 필요한 경우 데이터베이스 명령을 사용합니다.

참고

The view modified by collMod does not refer to materialized views. For discussion of on-demand materialized views, see $merge instead.

이 명령은 다음 환경에서 호스팅되는 배포에서 사용할 수 있습니다.

  • MongoDB Atlas: 클라우드에서의 MongoDB 배포를 위한 완전 관리형 서비스

참고

이 명령은 모든 MongoDB Atlas 클러스터에서 지원됩니다. 모든 명령에 대한 Atlas 지원에 관해 자세히 알아보려면 지원되지 않는 명령을 참조하십시오.

명령은 다음과 같은 구문을 가집니다:

db.runCommand(
{
collMod: <collection or view>,
<option1>: <value1>,
<option2>: <value2>,
...
}
)

For the <collection or view>, specify the name of a collection or view in the current database.

To change index options, specify either the key pattern or name of the existing index options you want to change:

db.runCommand( {
collMod: <collection>,
index: {
keyPattern: <index_spec> | name: <index_name>,
expireAfterSeconds: <number>, // Set the TTL expiration threshold
hidden: <boolean>, // Change index visibility in the query planner
prepareUnique: <boolean>, // Reject new duplicate index entries
unique: <boolean> // Convert an index to a unique index
},
dryRun: <boolean>
} )

If the index does not exist, the command errors with the message "cannot find index <name|keyPattern> for ns <db.collection>".

index

The index option can change the following properties of an existing index:

Index Property
설명

expireAfterSeconds

The number of seconds that determines the expiration threshold of a TTL Collection.

If successful, the command returns a document that contains:

  • expireAfterSeconds_new, the new value for expireAfterSeconds

  • expireAfterSeconds_old, the old value for expireAfterSeconds, if the index had a value for expireAfterSeconds before.

Modifying the index option expireAfterSeconds resets the $indexStats for the index.

MongoDB 5.0 이전에 생성된 TTL 인덱스를 사용하거나 MongDB 5.0에서 생성된 데이터를 5.0 이전 설치와 동기화하려는 경우 잘못된 구성 문제를 방지하려면 NaN을 사용하여 구성된 인덱스를 참조하세요.

TTL 인덱스 expireAfterSeconds 값은 02147483647 사이여야 합니다.

hidden

A boolean that determines whether the index is 숨김 or not from the query planner.

If the hidden value changes, the command returns a document that contains both the old and new values for the changed property: hidden_old and hidden_new.

However, if the hidden value has not changed (i.e. hiding an already hidden index or unhiding an already unhidden index), the command omits the hidden_old and hidden_new fields from the output.

To hide an index, you must have featureCompatibilityVersion set to 4.4 or greater.

Modifying the index option hidden resets the $indexStats for the index if the value changes.

prepareUnique

A boolean that determines whether the index will accept new duplicate entries.

New duplicate entries fail with DuplicateKey errors when prepareUnique is true. The resulting index can be converted to a unique index. To convert the index, use collMod with the unique option.

If an existing index is updated so that prepareUnique is true, the index is not checked for pre-existing, duplicate index entries.

버전 6.0에 추가.

unique

A boolean that determines whether the index is unique.

A value of false is not supported.

When unique is true, collMod scans the keyPattern index for duplicates and then converts it to a unique index if there are no duplicate index entries.

If duplicates are detected during the initial scan, collMod returns CannotConvertIndexToUnique and a list of conflicting documents. To convert an index with duplicate entries to a unique index, correct any reported conflicts and rerun collMod.

To end a conversion, set prepareUnique to false.

To see an example of how to convert a non-unique index to a unique index, see 기존 인덱스를 고유 인덱스로 변환.

버전 6.0에 추가.

dryRun

Default value: false

Only used when index.unique is true.

Before you convert a non-unique index to a unique index, you can run the collMod command with dryRun: true. If you do, MongoDB checks the collection for duplicate keys and returns any violations.

다음을 사용하세요. dryRun: true to confirm that you can convert an index to be unique without any errors.

validator

validator allows users to specify validation rules or expressions for a collection.

validator 옵션은 유효성 검사 규칙 또는 표현식을 지정하는 문서를 사용합니다. $near, $nearSphere, $text, $where을(를) 제외하고 쿼리 연산자와 동일한 연산자를 사용하여 표현식을 지정할 수 있습니다.

참고

  • 유효성 검사는 업데이트 및 삽입 중에 수행됩니다. 기존 문서는 수정될 때까지 유효성 검사를 거치지 않습니다.

  • admin, localconfig 데이터베이스의 컬렉션에는 유효성 검사기를 지정할 수 없습니다.

  • system.* 컬렉션에 대한 유효성 검사기를 지정할 수 없습니다.

validationLevel

The validationLevel determines how strictly MongoDB applies the validation rules to existing documents during an update.

"off"
삽입 또는 업데이트에 대한 유효성 검사가 없습니다.
"strict"
기본값 모든 삽입 및 모든 업데이트에 유효성 검사 규칙을 적용합니다.
"moderate"
기존의 유효한 문서에 대한 삽입 및 업데이트에 유효성 검사 규칙을 적용합니다. 기존의 유효하지 않은 문서에 대한 업데이트에는 규칙을 적용하지 마세요.

validationLevel 사용 예시는 기존 문서에 대한 유효성 검사 수준 지정을 참조하세요.

validationAction

The validationAction option determines whether to error on invalid documents or just warn about the violations but allow invalid documents.

중요

문서 유효성 검사는 validationLevel에 의해 결정된 문서에만 적용됩니다.

validationAction 사용 예시는 유효하지 않은 문서 처리 방법 선택을 참조하세요.

참고

The view modified by this command does not refer to materialized views. For discussion of on-demand materialized views, see $merge instead.

viewOn

The underlying source collection or view. The view definition is determined by applying the specified pipeline to this source.

Required if modifying a view on a MongoDB deployment that is running with access control.

pipeline

The 집계 파이프라인 that defines the view.

참고

보기 정의 pipeline에는 $out 또는 $merge 단계를 포함할 수 없습니다. 이 제한은 $lookup 단계 또는 $facet 단계에서 사용되는 파이프라인과 같은 임베디드 파이프라인에도 적용됩니다.

Required if modifying a view on a MongoDB deployment that is running with access control.

뷰 정의는 공개입니다. 즉, 뷰에 대한 db.getCollectionInfos()explain 작업에는 뷰를 정의하는 파이프라인이 포함됩니다. 따라서 뷰 정의에 민감한 필드와 값을 직접 참조하지 않는 것이 좋습니다.

db.runCommand( {
collMod: "myView",
viewOn: "activities",
pipeline: [
{ $match: { status: "Q" } },
{ $project: { user: 1, date: 1, description: 1} } ]
} )
expireAfterSeconds

참고

This is distinct from using the index option with the expireAfterSeconds property to change the expiration time for a TTL Collection.

To enable automatic document removal or modify the current expiration interval for a Time Series 컬렉션, change the expireAfterSeconds value:

db.runCommand( {
collMod: <collection>,
expireAfterSeconds: <number> | "off"
} )

세트 expireAfterSeconds to "off" to disable automatic removal, or a non-negative decimal number (>=0) to specify the number of seconds after which documents expire.

다음도 참조하세요.

granularity

To modify the granularity of a time series collection, you can increase timeseries.granularity from a shorter unit of time to a longer one:

db.runCommand( {
collMod: "weather24h",
timeseries: { granularity: "seconds" | "minutes" | "hours" }
} )

To update the custom bucketing fields bucketRoundingSeconds and bucketMaxSpanSeconds instead of granularity, include both custom fields in the collMod command and set them to the same value:

db.runCommand( {
collMod: "weather24h",
timeseries: {
bucketRoundingSeconds: 86400,
bucketMaxSpanSeconds: 86400
}
} )

You cannot decrease the granularity interval or the custom bucketing values.

중요

You cannot downgrade below MongoDB 6.3 if any time series collections explicitly specify the custom bucketing fields bucketMaxSpanSeconds and bucketRoundingSeconds. If possible, convert to the corresponding granularity. If you cannot, you must drop the collection before downgrading.

To convert a collection from custom bucketing to a granularity, value, both bucketMaxSpanSeconds and bucketRoundingSeconds must be less than or equal to the granularity equivalent:

granularity
bucketRoundingSeconds limit (inclusive)
bucketMaxSpanSeconds limit (inclusive)

seconds

60

3600

minutes

3600

86400

hours

86400

2592000

다음도 참조하세요.

버전 6.0에 추가.

Starting in MongoDB 6.0, you can resize a capped collection. To change a capped collection's maximum size in bytes, use the cappedSize option. To change the maximum number of documents in an existing capped collection, use the cappedMax option.

참고

You can't use these commands to resize the oplog. Use replSetResizeOplog instead.

cappedSize

Specifies a new maximum size, in bytes, for a capped collection. cappedSize must be greater than 0 and less than 1e+15 (1 PB).

cappedMax

Specifies a new maximum number of documents in a capped collection. Setting cappedMax less than or equal to 0 implies no limit.

For example, the following command sets the maximum size of a capped collection to 100000 bytes and sets the maximum number of documents in the collection to 500:

db.runCommand( {
collMod: <collection>,
cappedSize: 100000,
cappedMax: 500
} )

버전 6.0에 추가.

changeStreamPreAndPostImages

MongoDB 6.0부터는 변경 스트림 이벤트를 사용하여 문서의 변경 전후 버전(문서의 전후 이미지)을 출력할 수 있습니다.

  • 사전 이미지는 문서가 교체, 업데이트 또는 삭제되기 전의 문서입니다. 삽입된 문서에는 사전 이미지가 없습니다.

  • 사후 이미지는 문서가 삽입, 교체, 업데이트된 후의 문서입니다. 삭제된 문서에 대한 사후 이미지가 없습니다.

  • 활성화 changeStreamPreAndPostImages for a collection using db.createCollection(), create, or collMod.

To use collMod to enable change stream pre- and post-images for a collection, use the changeStreamPreAndPostImages field:

db.runCommand( {
collMod: <collection>,
changeStreamPreAndPostImages: { enabled: <boolean> }
} )

To enable change stream pre- and post-images for a collection, set changeStreamPreAndPostImages to true. For example:

db.runCommand( {
collMod: "orders",
changeStreamPreAndPostImages: { enabled: true }
} )

To disable change stream pre- and post-images for a collection, set changeStreamPreAndPostImages to false. For example:

db.runCommand( {
collMod: "orders",
changeStreamPreAndPostImages: { enabled: false }
} )

이미지가 다음과 같은 경우 변경 스트림 이벤트에 사전 및 사후 이미지를 사용할 수 없습니다.

  • 문서 업데이트 또는 삭제 작업 시 collection에서 활성화되지 않았습니다.

  • expireAfterSeconds에서 전후 이미지 보존 시간 설정 이후에 제거됩니다.

    • 다음 예시에서는 전체 클러스터에서 expireAfterSeconds100초로 설정합니다.

      use admin
      db.runCommand( {
      setClusterParameter:
      { changeStreamOptions: {
      preAndPostImages: { expireAfterSeconds: 100 }
      } }
      } )
    • 다음 예시에서는 expireAfterSeconds 등 현재 changeStreamOptions 설정을 반환합니다.

      db.adminCommand( { getClusterParameter: "changeStreamOptions" } )
    • expireAfterSecondsoff로 설정하면 기본 보존 정책이 사용되며, 해당 변경 스트림 이벤트가 oplog에서 제거될 때까지 사전 및 사후 이미지가 보존됩니다.

    • 변경 스트림 이벤트가 oplog에서 제거되면 expireAfterSeconds 사전 및 사후 이미지 보존 시간에 관계없이 해당 사전 및 사후 이미지도 삭제됩니다.

추가 고려 사항

  • 전후 이미지를 활성화하면 저장 공간이 소모되고 처리 시간이 늘어납니다. 필요한 경우에만 전후 이미지를 활성화하세요.

  • 변경 스트림 이벤트 크기를 16메비바이트 미만으로 제한합니다. 이벤트 크기를 제한하려면 다음을 수행하면 됩니다.

    • 문서 크기를 8메가바이트로 제한합니다. updateDescription과 같은 다른 변경 스트림 이벤트 필드가 크지 않은 경우 변경 스트림 출력에서 사전 및 사후 이미지를 동시에 요청할 수 있습니다.

    • updateDescription과 같은 다른 변경 스트림 이벤트 필드가 크지 않은 경우, 최대 16메비바이트 문서에 대해 변경 스트림 출력에서 사후 이미지만 요청합니다.

    • 다음과 같은 경우 최대 16메비바이트의 문서에 대해 변경 스트림 출력에서 사전 이미지만 요청합니다.

      • 문서 업데이트가 문서 구조나 내용의 작은 부분에만 영향을 미칩니다. 그리고

      • replace 변경 이벤트를 발생시키지 않습니다. replace 이벤트에는 항상 후이미지가 포함됩니다.

  • 사전 이미지를 요청하려면 db.collection.watch()에서 fullDocumentBeforeChangerequired 또는 whenAvailable로 설정합니다. 사후 이미지를 요청하려면 동일한 방법으로 fullDocument를 설정합니다.

  • 사전 이미지가 config.system.preimages 컬렉션에 기록됩니다.

    • config.system.preimages collection은 커질 수 있습니다. collection 크기를 제한하려면 앞서 표시된 대로 사전 이미지에 대해 expireAfterSeconds 시간을 설정할 수 있습니다.

    • 사전 이미지는 백그라운드 프로세스가 비동기적으로 제거합니다.

중요

이전 버전과 호환되지 않는 기능

Starting in MongoDB 6.0, if you are using document pre- and post-images for change streams, you must disable changeStreamPreAndPostImages for each collection using the collMod command before you can downgrade to an earlier MongoDB version.

다음도 참조하세요.

comment

Optional. You can attach a comment to this command. The comment must be a top-level field and can be any valid BSON type. The comment that you specify appears alongside records of this command in the following locations:

w

Optional. A document expressing the 쓰기 고려 of the collMod command.

Omit to use the default write concern.

If the deployment enforces authentication/authorization, you must have the following privilege to run the collMod command:

작업
필수 권한

Modify a non-capped collection

collMod in the database

Modify a view

collMod in the database and either:

  • no find on the view to modify, or

  • both find on the view to modify and find on the source collection/view.

The built-in role dbAdmin provides the required privileges.

The collMod command obtains a collection lock on the specified collection for the duration of the operation.

The following example updates the expireAfterSeconds property of an existing TTL index { lastAccess: 1 } on a collection named user_log. The current expireAfterSeconds property for the index is set to 1800 seconds (or 30 minutes) and the example changes the value to 3600 seconds (or 60 minutes).

db.runCommand({
collMod: "user_log",
index: {
keyPattern: { lastAccess: 1 },
expireAfterSeconds: 3600
}
})

If successful, the operation returns a document that includes both the old and new value for the changed property:

{ "expireAfterSeconds_old" : 1800, "expireAfterSeconds_new" : 3600, "ok" : 1 }

참고

인덱스를 숨기려면 featureCompatibilityVersion5.0 이상으로 설정해야 합니다.

The following example hides an existing index on the orders collection. Specifically, the operation hides the index with the specification { shippedDate: 1 } from the query planner.

db.runCommand( {
collMod: "orders",
index: {
keyPattern: { shippedDate: 1 },
hidden: true
}
} )

If successful, the operation returns a document that includes both the old and new value for the changed property:

{ "hidden_old" : false, "hidden_new" : true, "ok" : 1 }

참고

If the operation is successful but the hidden value has not changed (specifically, hiding an already hidden index or unhiding an already unhidden index), the command omits the hidden_old and hidden_new fields from the output.

To hide a text index, you must specify the index by name and not by keyPattern.

다음도 참조하세요.