콜모드
이 페이지의 내용
정의
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 지원에 관해 자세히 알아보려면 지원되지 않는 명령을 참조하십시오.
MongoDB Enterprise: MongoDB의 구독 기반 자체 관리 버전
MongoDB Community: MongoDB의 소스 사용 가능 무료 자체 관리 버전
구문
명령은 다음과 같은 구문을 가집니다:
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.
옵션
Change Index Properties
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 forexpireAfterSeconds
expireAfterSeconds_old
, the old value forexpireAfterSeconds
, if the index had a value forexpireAfterSeconds
before.
Modifying the index option
expireAfterSeconds
resets the$indexStats
for the index.MongoDB 5.0 이전에 생성된 TTL 인덱스를 사용하거나 MongDB 5.0에서 생성된 데이터를 5.0 이전 설치와 동기화하려는 경우 잘못된 구성 문제를 방지하려면 NaN을 사용하여 구성된 인덱스를 참조하세요.
TTL 인덱스
expireAfterSeconds
값은0
과2147483647
사이여야 합니다.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
andhidden_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 thehidden_old
andhidden_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
istrue
. The resulting index can be converted to a unique index. To convert the index, usecollMod
with theunique
option.If an existing index is updated so that
prepareUnique
istrue
, 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
istrue
,collMod
scans thekeyPattern
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
returnsCannotConvertIndexToUnique
and a list of conflicting documents. To convert an index with duplicate entries to a unique index, correct any reported conflicts and reruncollMod
.To end a conversion, set
prepareUnique
tofalse
.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
istrue
.Before you convert a non-unique index to a unique index, you can run the
collMod
command withdryRun: 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.
Validate Documents
validator
validator
allows users to specify validation rules or expressions for a collection.validator
옵션은 유효성 검사 규칙 또는 표현식을 지정하는 문서를 사용합니다.$near
,$nearSphere
,$text
,$where
을(를) 제외하고 쿼리 연산자와 동일한 연산자를 사용하여 표현식을 지정할 수 있습니다.
참고
유효성 검사는 업데이트 및 삽입 중에 수행됩니다. 기존 문서는 수정될 때까지 유효성 검사를 거치지 않습니다.
admin
,local
및config
데이터베이스의 컬렉션에는 유효성 검사기를 지정할 수 없습니다.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 toerror
on invalid documents or justwarn
about the violations but allow invalid documents.중요
문서 유효성 검사는
validationLevel
에 의해 결정된 문서에만 적용됩니다.validationAction
사용 예시는 유효하지 않은 문서 처리 방법 선택을 참조하세요.
Modify Views
참고
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.
참고
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} } ] } )
Modify Time Series Collections
expireAfterSeconds
참고
This is distinct from using the
index
option with theexpireAfterSeconds
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
andbucketMaxSpanSeconds
instead ofgranularity
, include both custom fields in thecollMod
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
andbucketRoundingSeconds
. If possible, convert to the correspondinggranularity
. If you cannot, you must drop the collection before downgrading.To convert a collection from custom bucketing to a
granularity
, value, bothbucketMaxSpanSeconds
andbucketRoundingSeconds
must be less than or equal to thegranularity
equivalent:granularity
bucketRoundingSeconds
limit (inclusive)bucketMaxSpanSeconds
limit (inclusive)seconds
60
3600
minutes
3600
86400
hours
86400
2592000
다음도 참조하세요.
Resize a Capped Collection
버전 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 than0
and less than1e+15
(1 PB).
cappedMax
Specifies a new maximum number of documents in a capped collection. Setting
cappedMax
less than or equal to0
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 } )
전후 이미지를 포함하는 문서의 Change Streams
버전 6.0에 추가.
MongoDB 6.0부터는 변경 스트림 이벤트를 사용하여 문서의 변경 전후 버전(문서의 전후 이미지)을 출력할 수 있습니다.
사전 이미지는 문서가 교체, 업데이트 또는 삭제되기 전의 문서입니다. 삽입된 문서에는 사전 이미지가 없습니다.
사후 이미지는 문서가 삽입, 교체, 업데이트된 후의 문서입니다. 삭제된 문서에 대한 사후 이미지가 없습니다.
활성화
changeStreamPreAndPostImages
for a collection usingdb.createCollection()
,create
, orcollMod
.
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
에서 전후 이미지 보존 시간 설정 이후에 제거됩니다.다음 예시에서는 전체 클러스터에서
expireAfterSeconds
를100
초로 설정합니다.use admin db.runCommand( { setClusterParameter: { changeStreamOptions: { preAndPostImages: { expireAfterSeconds: 100 } } } } ) 다음 예시에서는
expireAfterSeconds
등 현재changeStreamOptions
설정을 반환합니다.db.adminCommand( { getClusterParameter: "changeStreamOptions" } ) expireAfterSeconds
를off
로 설정하면 기본 보존 정책이 사용되며, 해당 변경 스트림 이벤트가 oplog에서 제거될 때까지 사전 및 사후 이미지가 보존됩니다.변경 스트림 이벤트가 oplog에서 제거되면
expireAfterSeconds
사전 및 사후 이미지 보존 시간에 관계없이 해당 사전 및 사후 이미지도 삭제됩니다.
추가 고려 사항
전후 이미지를 활성화하면 저장 공간이 소모되고 처리 시간이 늘어납니다. 필요한 경우에만 전후 이미지를 활성화하세요.
변경 스트림 이벤트 크기를 16메비바이트 미만으로 제한합니다. 이벤트 크기를 제한하려면 다음을 수행하면 됩니다.
문서 크기를 8메가바이트로 제한합니다.
updateDescription
과 같은 다른 변경 스트림 이벤트 필드가 크지 않은 경우 변경 스트림 출력에서 사전 및 사후 이미지를 동시에 요청할 수 있습니다.
updateDescription
과 같은 다른 변경 스트림 이벤트 필드가 크지 않은 경우, 최대 16메비바이트 문서에 대해 변경 스트림 출력에서 사후 이미지만 요청합니다.다음과 같은 경우 최대 16메비바이트의 문서에 대해 변경 스트림 출력에서 사전 이미지만 요청합니다.
문서 업데이트가 문서 구조나 내용의 작은 부분에만 영향을 미칩니다. 그리고
replace
변경 이벤트를 발생시키지 않습니다.replace
이벤트에는 항상 후이미지가 포함됩니다.
사전 이미지를 요청하려면
db.collection.watch()
에서
fullDocumentBeforeChange
를required
또는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.
다음도 참조하세요.
변경 스트림 이벤트 및 출력에 대해서는 변경 이벤트를 참조하세요.
컬렉션에서 변경 사항을 확인하려면
db.collection.watch()
를 참조하세요.
변경 스트림s 출력에 대한 전체 예시는 전후 이미지를 포함하는 문서의 변경 스트림s를 참조하세요.
Attach 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:
mongod 로그 메시지(
attr.command.cursor.comment
필드).Database profiler output, in the
command.comment
field.currentOp
{command.comment
5} 필드에 출력을 입력합니다.
쓰기 고려
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 |
|
Modify a 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.
예시
Change Expiration Value for Indexes
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 }
Hide an Index from the Query Planner
참고
인덱스를 숨기려면 featureCompatibilityVersion을 5.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
.
다음도 참조하세요.