collMod
On this page本页内容
Definition定义Syntax语法Options选项Change Index Properties更改索引属性Validate Documents验证文档Modify Views修改视图Modify Time Series Collections修改时间序列集合Resize a Capped Collection调整封顶集合的大小Change Streams with Document Pre- and Post-Images使用文档前后映像更改流Attach Comment附加注释Write Concern撰写关注事项Access Control访问控制Behavior行为Resource Locking资源锁定Examples实例Change Expiration Value for Indexes更改索引的过期值Hide an Index from the Query Planner在查询规划器中隐藏索引Convert an Existing Index to a Unique Index将现有索引转换为唯一索引
Definition定义
collMod
-
collMod
makes it possible to add options to a collection or to modify view definitions.可以向集合添加选项或修改视图定义。TipIn在mongosh
, this command can also be run through thehideIndex()
andunhideIndex()
helper methods.mongosh
中,该命令也可以通过hideIndex()
和unhideIndex()
助手方法运行。Helper methods are convenient for助手方法对mongosh
users, but they may not return the same level of information as database commands.mongosh
用户来说很方便,但它们可能不会返回与数据库命令相同级别的信息。In cases where the convenience is not needed or the additional return fields are required, use the database command.如果不需要方便,或者需要额外的返回字段,请使用数据库命令。
Syntax语法
The command has the following syntax:该命令具有以下语法:
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.<collection or view>
,指定当前数据库中集合或视图的名称。
Options选项
Change Index Properties更改索引属性
index
-
Theindex
option can change the following properties of an existing index:index
选项可以更改现有索引的以下属性:Index Property索引属性Description描述expireAfterSeconds
The number of seconds that determines the expiration threshold of a TTL Collection.确定TTL集合的过期阈值的秒数。
If successful, the command returns a document that contains:如果成功,该命令将返回一个包含以下内容的文档:expireAfterSeconds_new
, the new value forexpireAfterSeconds
expireAfterSeconds_new
,expireAfterSeconds
的新值expireAfterSeconds_old
, the old value for,expireAfterSeconds
, if the index had a value forexpireAfterSeconds
before.expireAfterSeconds
的旧值,如果索引之前有expireAfterSeconds
的值。
Modifying the index option修改索引选项expireAfterSeconds
resets the$indexStats
for the index.expireAfterSeconds
会重置索引的$indexStats
。
If you use TTL indexes created before MongoDB 5.0, or if you want to sync data created in MongDB 5.0 with a pre-5.0 installation, see Indexes Configured Using NaN to avoid misconfiguration issues.如果您使用MongoDB 5.0之前创建的TTL索引,或者如果您希望将MongDB 5.0中创建的数据与5.0之前的安装同步,请参阅使用NaN配置的索引以避免配置错误问题。
The TTL indexTTL索引expireAfterSeconds
value must be within0
and2147483647
inclusive.expireAfterSeconds
值必须介于0
和2147483647
之间(包括0
和2147463647
)。hidden
A boolean that determines whether the index is hidden 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
.hidden
值发生更改,该命令将返回一个文档,其中包含更改后的特性的旧值和新值:hidden_old
和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 thehidden_old
andhidden_new
fields from the output.hidden
值没有更改(即隐藏已隐藏的索引或取消隐藏已取消隐藏的索引),则该命令会从输出中省略hidden_old
和hidden_new
字段。
To hide an index, you must have featureCompatibilityVersion set to若要隐藏索引,必须将4.4
or greater.featureCompatibilityVersion
设置为4.4
或更高版本。
Modifying the index option如果值发生更改,修改hidden
resets the$indexStats
for the index if the value changes.hidden
的索引选项将重置索引的$indexStats
。
New in version 4.4.4.4版新增。prepareUnique
A boolean that determines whether the index will accept new duplicate entries.一个布尔值,用于确定索引是否接受新的重复条目。
New duplicate entries fail with DuplicateKey errors when当prepareUnique
istrue
.prepareUnique
为true
时,新的重复条目将失败,并出现DuplicateKey错误。The resulting index can be converted to a unique index. To convert the index, use生成的索引可以转换为唯一索引。要转换索引,请使用带有collMod
with theunique
option.unique
选项的collMod
。
If an existing index is updated so that如果更新现有索引以使prepareUnique
istrue
, the index is not checked for pre-existing, duplicate index entries.prepareUnique
为true
,则不会检查该索引中是否存在预先存在的重复索引条目。
New in version 6.0.6.0版新增。unique
A boolean that determines whether or not the index is unique.一个布尔值,用于确定索引是否唯一。NoteMust be set to必须设置为true
.false
is not supported.true
。不支持false
。When当unique
istrue
,collMod
scans thekeyPattern
index for duplicates and then converts it to a unique index if there are no duplicate index entries.unique
为true
时,collMod
扫描keyPattern
索引以查找重复项,然后在没有重复索引项的情况下将其转换为唯一索引。
If duplicates are detected during the initial scan,如果在初始扫描期间检测到重复,collMod
returnsCannotConvertIndexToUnique
and a list of conflicting documents.collMod
将返回CannotConvertIndexToUnique
和冲突文档列表。To convert an index with duplicate entries to a unique index, correct any reported conflicts and rerun若要将包含重复项的索引转换为唯一索引,请更正所有报告的冲突,然后重新运行collMod
.
To end a conversion, setprepareUnique
tofalse
.collMod
。
若要结束转换,请将prepareUnique
设置为false
。
New in version 6.0.6.0版新增。To change index options, specify either the key pattern or name of the existing index and the index option or options you wish to change:要更改索引选项,请指定现有索引的键模式或名称以及要更改的一个或多个索引选项:db.runCommand( {
collMod: <collection>,
index: {
keyPattern: <index_spec> || name: <index_name>,
expireAfterSeconds: <number>, //Set the TTL expiration threshold设置TTL过期阈值
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将索引转换为唯一索引
}
} )If the index does not exist, the command errors with the message如果索引不存在,则命令将出错,并显示消息"cannot find index <name|keyPattern> for ns <db.collection>"
."cannot find index <name|keyPattern> for ns <db.collection>"
。TipSee also:另请参阅:
Validate Documents验证文档
validator
-
validator
allows users to specify validation rules or expressions for a collection.允许用户为集合指定验证规则或表达式。Thevalidator
option takes a document that specifies the validation rules or expressions.validator
选项接受一个指定验证规则或表达式的文档。You can specify the expressions using the same operators as the query operators with the exception of您可以使用与查询运算符相同的运算符指定表达式,但$near
,$nearSphere
,$text
, and$where
.$near
、$nearSphere
、$text
和$where
除外。NoteValidation occurs during updates and inserts.在更新和插入期间进行验证。Existing documents do not undergo validation checks until modification.现有文件在修改前不会进行验证检查。You cannot specify a validator for collections in the不能为admin
,local
, andconfig
databases.admin
数据库、local
数据库和config
数据库中的集合指定验证器。You cannot specify a validator for不能为system.*
collections.system.*
集合指定验证器。
validationLevel
-
ThevalidationLevel
determines how strictly MongoDB applies the validation rules to existing documents during an update.validationLevel
决定了MongoDB在更新过程中对现有文档应用验证规则的严格程度。validationLevel
Description描述"off"
No validation for inserts or updates.没有对插入或更新进行验证。"strict"
Default默认值。Apply validation rules to all inserts and all updates.将验证规则应用于所有插入和所有更新。"moderate"
Apply validation rules to inserts and to updates on existing valid documents.将验证规则应用于现有有效文档的插入和更新。Do not apply rules to updates on existing invalid documents.不要将规则应用于现有无效文档的更新。To see an example that uses要查看使用validationLevel
, see Specify Validation Level for Existing Documents.validationLevel
的示例,请参阅指定现有文档的验证级别。
validationAction
-
ThevalidationAction
option determines whether toerror
on invalid documents or justwarn
about the violations but allow invalid documents.validationAction
选项决定是在无效文档上出错,还是只是警告违规行为,但允许无效文档。ImportantValidation of documents only applies to those documents as determined by the文件的验证仅适用于由validationLevel
.validationLevel
确定的那些文件。To see an example that uses要查看使用validationAction
, see Choose How to Handle Invalid Documents.validationAction
的示例,请参阅选择如何处理无效文档。
Modify Views修改视图
viewOn
-
The underlying source collection or view. The view definition is determined by applying the specified基础源集合或视图。视图定义是通过将指定的pipeline
to this source.pipeline
应用到此源来确定的。Required if modifying a view on a MongoDB deployment that is running with access control.如果修改使用访问控制运行的MongoDB部署的视图,则为必需项。
pipeline
-
The aggregation pipeline that defines the view.定义视图的聚合管道。NoteRequired if modifying a view on a MongoDB deployment that is running with access control.如果修改使用访问控制运行的MongoDB部署的视图,则为必需项。The view definition is public; i.e.视图定义是公开的;亦即db.getCollectionInfos()
andexplain
operations on the view will include the pipeline that defines the view. As such, avoid referring directly to sensitive fields and values in view definitions.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
- Note
This is distinct from using the这与使用index
option with theexpireAfterSeconds
property to change the expiration time for a TTL Collection.index
选项和expireAfterSeconds
属性来更改TTL集合的过期时间不同。To enable automatic document removal or modify the current expiration interval for a time series collection, change the要启用自动文档删除或修改时间序列集合的当前过期间隔,请更改expireAfterSeconds
value:expireAfterSeconds
值:db.runCommand( {
collMod: <collection>,
expireAfterSeconds: <number> || "off"
} )Set将expireAfterSeconds
to"off"
to disable automatic removal, or a non-negative decimal number (>=0
) to specify the number of seconds after which documents expire.expireAfterSeconds
设置为"off"
以禁用自动删除,或将非负十进制数(>=0
)设置为指定文档过期的秒数。
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:timeseries.granularity
从较短的时间单位增加到较长的时间单位:db.runCommand({
collMod: "weather24h",
timeseries: { granularity: "seconds" || "minutes" || "hours" }
})To update the custom bucketing parameters要更新自定义bucketRoundingSeconds
andbucketMaxSpanSeconds
instead ofgranularity
, include both custom parameters in thecollMod
command and set them to the same value:bucketRoundingSeconds
和bucketMaxSpanSeconds
参数而不是granularity
,请在collMod
命令中包含这两个自定义参数,并将它们设置为相同的值:db.runCommand({
collMod: "weather24h",
timeseries: {
bucketRoundingSeconds: "86400",
bucketMaxSpanSeconds: "86400"
}
})You cannot decrease the granularity interval or the custom bucketing values.不能减少粒度间隔或自定义分段值。ImportantYou cannot downgrade below MongoDB 6.3 if any time series collections explicitly specify the custom bucketing parameters如果任何时间序列集合明确指定了自定义bucketMaxSpanSeconds
andbucketRoundingSeconds
.bucketMaxSpanSeconds
和bucketRoundingSeconds
,则不能降级到MongoDB 6.3以下。If possible, convert to the corresponding如果可能,请转换为相应的granularity
. If you cannot, you must drop the collection before downgrading.granularity
。如果不能,则必须在降级前删除集合。To convert a collection from custom bucketing to a要将集合从自定义bucketing转换为granularity
, value, bothbucketMaxSpanSeconds
andbucketRoundingSeconds
must be less than or equal to thegranularity
equivalent:granularity
值,bucketMaxSpanSeconds
和bucketRoundingSeconds
都必须小于或等于等效粒度:granularity
bucketRoundingSeconds
and和bucketMaxSpanSeconds
limit (inclusive)限额(含)seconds
60 minutes
3600 hours
86400 TipSee also:另请参阅:
Resize a Capped Collection调整封顶集合的大小
New in version 6.0. 6.0版新增。
Starting in MongoDB 6.0, you can resize a capped collection. 从MongoDB 6.0开始,您可以调整带帽集合的大小。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.cappedSize
选项。要更改现有已封顶集合中的最大文档数,请使用cappedMax
选项。
You can't use these commands to resize the oplog. 您不能使用这些命令来调整操作日志的大小。Use 请改用replSetResizeOplog
instead.replSetResizeOplog
。
cappedSize
-
Specifies a new maximum size, in bytes, for a capped collection.为有上限的集合指定新的最大大小(以字节为单位)。cappedSize
must be greater than0
and less than1e+15
(1 PB).cappedSize
必须大于0
且小于1e+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.cappedMax
设置为小于或等于0意味着没有限制。
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:例如,以下命令将带上限的集合的最大大小设置为100000字节,并将集合中文档的最大数量设置为500:
db.runCommand( {
collMod: <collection>,
cappedSize: 100000,
cappedMax: 500
} )
Change Streams with Document Pre- and Post-Images使用文档前后映像更改流
New in version 6.0. 6.0版新增。
changeStreamPreAndPostImages
Starting in MongoDB 6.0, you can use change stream events to output the version of a document before and after changes (the document pre- and post-images):从MongoDB 6.0开始,您可以使用更改流事件来输出更改前后文档的版本(文档前后映像):
The pre-image is the document before it was replaced, updated, or deleted. There is no pre-image for an inserted document.前映像是在文档被替换、更新或删除之前的文档。插入的文档没有前映像。The post-image is the document after it was inserted, replaced, or updated. There is no post-image for a deleted document.后映像是插入、替换或更新后的文档。已删除的文档没有后映像。- Enable
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:collMod
为集合启用更改流前映像和后映像,请使用changeStreamPreAndPostImages
字段:
db.runCommand( {
collMod: <collection>,
changeStreamPreAndPostImages: { enabled: <boolean> }
} )
To enable change stream pre- and post-images for a collection, set 要启用集合的更改流前映像和后映像,请将changeStreamPreAndPostImages
to true
. changeStreamPreAndPostImages
设置为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
. changeStreamPreAndPostImages
设置为false
。For example:例如:
db.runCommand( {
collMod: "orders",
changeStreamPreAndPostImages: { enabled: false }
} )
Pre- and post-images are not available for a change stream event if the images were:如果映像为以下情况,则前映像和后映象对更改流事件不可用:
Not enabled on the collection at the time of a document update or delete operation.文档更新或删除操作时未在集合上启用。Removed after the pre- and post-image retention time set in在expireAfterSeconds
.expireAfterSeconds
中设置的前映像和后映像后保留时间之后删除。The following example sets以下示例将expireAfterSeconds
to100
seconds:expireAfterSeconds
设置为100
秒:use admin
db.runCommand( {
setClusterParameter:
{ changeStreamOptions: { preAndPostImages: { expireAfterSeconds: 100 } } }
} )The following example returns the current以下示例返回当前changeStreamOptions
settings, includingexpireAfterSeconds
:changeStreamOptions
设置,包括expireAfterSeconds
:db.adminCommand( { getClusterParameter: "changeStreamOptions" } )
Setting将expireAfterSeconds
tooff
uses the default retention policy: pre- and post-images are retained until the corresponding change stream events are removed from the oplog.expireAfterSeconds
设置为off
使用默认的保留策略:保留前映像和后映像,直到从操作日志中删除相应的更改流事件。If a change stream event is removed from the oplog, then the corresponding pre- and post-images are also deleted regardless of the如果更改流事件从操作日志中删除,则相应的前映像和后映像也将被删除,而不管映像前和后映像的保留时间是expireAfterSeconds
pre- and post-image retention time.expireAfterSeconds
。
Additional considerations:其他注意事项:
Enabling pre- and post-images consumes storage space and adds processing time. Only enable pre- and post-images if you need them.启用前映像和后映像会消耗存储空间并增加处理时间。只有在需要时才启用前映像和后映像。Limit the change stream event size to less than 16 megabytes. To limit the event size, you can:将更改流事件大小限制为小于16兆字节。要限制事件大小,您可以:Limit the document size to 8 megabytes.将文档大小限制为8兆字节。You can request pre- and post-images simultaneously in the change stream output if other change stream event fields like如果其他变更流事件字段(如updateDescription
are not large.updateDescription
)不大,则可以在变更流输出中同时请求前映像和后映像。Request only post-images in the change stream output for documents up to 16 megabytes if other change stream event fields like如果其他更改流事件字段(如updateDescription
are not large.updateDescription
)不太大,则请求在更改流输出中为高达16兆字节的文档后映像。Request only pre-images in the change stream output for documents up to 16 megabytes if:如果出现以下情况,则仅在更改流输出中请求高达16兆字节的文档的前映像:document updates affect only a small fraction of the document structure or content, and文档更新只影响文档结构或内容的一小部分,并且do not cause a不要引起replace
change event. Areplace
event always includes the post-image.replace
更改事件。replace
事件始终包括后映像。
To request a pre-image, you set若要请求前映像,请在fullDocumentBeforeChange
torequired
orwhenAvailable
indb.collection.watch()
. To request a post-image, you setfullDocument
using the same method.db.collection.watch()
中将fullDocumentBeforeChange
设置为required
或whenAvailable
。若要请求后映像,请使用相同的方法设置fullDocument
。Pre-images are written to the前映像将写入config.system.preimages
collection.config.system.preimages
集合。Theconfig.system.preimages
collection may become large. To limit the collection size, you can setexpireAfterSeconds
time for the pre-images as shown earlier.config.system.preimages
集合可能会变大。要限制集合大小,您可以为前映像设置expireAfterSeconds
时间,如前所示。Pre-images are removed asynchronously by a background process.前映像通过后台进程异步移除。
Backward-Incompatible Feature向后不兼容功能
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 从MongoDB 6.0开始,如果您对更改流使用文档前映像和后映像,则必须使用collMod
command before you can downgrade to an earlier MongoDB version.collMod
命令为每个集合禁用changeStreamPreAndPostImages
,然后才能降级到早期的MongoDB版本。
See also: 另请参阅:
For change stream events and output, see Change Events.有关更改流事件和输出,请参阅更改事件。To watch a collection for changes, see要监视集合的更改,请参阅db.collection.watch()
.db.collection.watch()
。For complete examples with the change stream output, see Change Streams with Document Pre- and Post-Images.有关更改流输出的完整示例,请参阅文档前后映像的更改流。
Attach Comment附加注释
New in version 4.4. 4.4版新增。
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. 注释必须是顶级字段,并且可以是任何有效的BSON类型。The comment that you specify appears alongside records of this command in the following locations:指定的注释将显示在此命令的记录旁边的以下位置:
mongod log messages, in theattr.command.cursor.comment
field.mongod
日志消息,在attr.command.cursor.comment
字段中。Database profiler output, in thecommand.comment
field.command.comment
字段中的数据库探查器输出。currentOp
output, in the输出,在command.comment
field.command.comment
字段中。
Write Concern撰写关注事项
w
Optional. 可选的。A document expressing the write concern of the 表示collMod
command.collMod
命令的写入关注的文档。
Omit to use the default write concern.忽略使用默认的写入关注。
Access Control访问控制
If the deployment enforces authentication/authorization, you must have the following privilege to run the 如果部署强制执行身份验证/授权,则必须具有以下权限才能运行collMod
command:collMod
命令:
collMod in the databasecollMod | |
collMod in the database and either: collMod ,以及以下任一个:
|
The built-in role 内置角色dbAdmin
provides the required privileges.dbAdmin
提供所需的权限。
Behavior行为
Resource Locking资源锁定
The collMod
command obtains a collection lock on the specified collection for the duration of the operation.collMod
命令在操作期间获取指定集合的集合锁定。
Examples实例
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
. user_log
的集合上现有TTL索引{ lastAccess: 1 }
的expireAfterSeconds
属性。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).expireAfterSeconds
属性设置为1800
秒(或30
分钟),示例将该值更改为3600
秒(或60
分钟)。
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在查询规划器中隐藏索引
To hide an index, you must have featureCompatibilityVersion set to 若要隐藏索引,必须将4.4
or greater. featureCompatibilityVersion
设置为4.4
或更高版本。However, once hidden, the index remains hidden even with 然而,一旦隐藏,即使在MongoDB 4.4二进制文件中将featureCompatibilityVersion
set to 4.2
on MongoDB 4.4 binaries.featureCompatibilityVersion
设置为4.2
,索引也会保持隐藏状态。
The following example hides an existing index on the 以下示例隐藏orders
collection. orders
集合上的现有索引。Specifically, the operation hides the index with the specification 具体地说,该操作向查询计划器隐藏具有规范{ shippedDate: 1 }
from the query planner.{ shippedDate: 1 }
的索引。
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 (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.hidden
值没有更改(即隐藏已隐藏的索引或取消隐藏已取消隐藏的索引),则该命令将从输出中省略hidden_old
和hidden_new
字段。
To hide a text index, you must specify the index by 若要隐藏文本索引,必须按name
and not by keyPattern
.name
而不是按keyPattern
指定索引。
See also: 另请参阅:
Convert an Existing Index to a Unique Index将现有索引转换为唯一索引
Create the 创建apples
collection:apples
集合:
db.apples.insertMany( [
{ type: "Delicious", quantity: 12 },
{ type: "Macintosh", quantity: 13 },
{ type: "Delicious", quantity: 13 },
{ type: "Fuji", quantity: 15 },
{ type: "Washington", quantity: 10 },
] )
Add a single field index on 在type
:type
上添加单个字段索引:
db.apples.createIndex( { type: 1 } )
Prepare the index on the 准备type
field for conversion:type
字段上的索引以进行转换:
db.runCommand( {
collMod: "apples",
index: {
keyPattern: { type: 1 },
prepareUnique: true
}
} )
The existing index may contain duplicate entries, but it will not accept new documents that duplicate an index entry when 现有索引可能包含重复的条目,但当prepareUnique
is true
.prepareUnique
为true
时,它将不接受与索引条目重复的新文档。
Try to insert a document with a duplicate index value:尝试插入索引值重复的文档:
db.apples.insertOne( { type: "Delicious", quantity: 200 } )
The operation returns an error. The index will not accept new duplicate entries.该操作返回一个错误。索引将不接受新的重复条目。
Use the 使用unique
option to convert the index to a unique index. unique
选项可以将索引转换为唯一索引。collMod
checks the collection for duplicate index entries before converting the index:在转换索引之前,请检查集合中是否存在重复的索引项:
db.runCommand( {
collMod: "apples",
index: {
keyPattern: { type: 1 },
unique: true
}
} )
The response to this operation varies by driver. You will always receive an error message about the duplicate entries.对该操作的响应因驾驶员而异。您将始终收到关于重复条目的错误消息。
"errmsg" : "Cannot convert the index to unique. Please resolve
conflicting documents before running collMod again."
Some drivers also return a list of 一些驱动程序还返回重复项的ObjectIds
for the duplicate entries:ObjectId
列表:
{
"ok" : 0,
"errmsg" : "Cannot convert the index to unique. Please resolve \
conflicting documents before running collMod again.",
"code" : 359,
"codeName" : "CannotConvertIndexToUnique",
"violations" : [
{
"ids" : [
ObjectId("62a2015777e2d47c4da33146"),
ObjectId("62a2015777e2d47c4da33148")
]
}
]
}
To complete the conversion, modify the duplicate entries to remove any conflicts and re-run 要完成转换,请修改重复的条目以删除任何冲突,并使用collMod()
with the unique
option.unique
选项重新运行collMod()
。