Docs HomeMongoDB Manual

collMod

Definition定义

collMod

collMod makes it possible to add options to a collection or to modify view definitions.可以向集合添加选项或修改视图定义。

Tip

In mongosh, this command can also be run through the hideIndex() and unhideIndex() 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.如果不需要方便,或者需要额外的返回字段,请使用数据库命令。

Note

The view modified by this command does not refer to materialized views. 此命令修改的视图不引用物化视图。For discussion of on-demand materialized views, see $merge instead.有关按需物化视图的讨论,请参阅$merge

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

The index option can change the following properties of an existing index:index选项可以更改现有索引的以下属性:

Index Property索引属性Description描述
expireAfterSecondsThe 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 for expireAfterSecondsexpireAfterSeconds_newexpireAfterSeconds的新值
  • expireAfterSeconds_old, the old value for expireAfterSeconds, if the index had a value for expireAfterSeconds 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 index expireAfterSeconds value must be within 0 and 2147483647 inclusive. TTL索引expireAfterSeconds值必须介于02147483647之间(包括02147463647)。
hiddenA 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 and hidden_new.如果hidden值发生更改,该命令将返回一个文档,其中包含更改后的特性的旧值和新值:hidden_oldhidden_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.但是,如果hidden值没有更改(即隐藏已隐藏的索引或取消隐藏已取消隐藏的索引),则该命令会从输出中省略hidden_oldhidden_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版新增。
prepareUniqueA boolean that determines whether the index will accept new duplicate entries.一个布尔值,用于确定索引是否接受新的重复条目。
New duplicate entries fail with DuplicateKey errors when prepareUnique is true. prepareUniquetrue时,新的重复条目将失败,并出现DuplicateKey错误。The resulting index can be converted to a unique index. To convert the index, use collMod with the unique option.生成的索引可以转换为唯一索引。要转换索引,请使用带有unique选项的collMod
If an existing index is updated so that prepareUnique is true, the index is not checked for pre-existing, duplicate index entries. 如果更新现有索引以使prepareUniquetrue,则不会检查该索引中是否存在预先存在的重复索引条目。
New in version 6.0. 6.0版新增。
uniqueA boolean that determines whether or not the index is unique. 一个布尔值,用于确定索引是否唯一。
Note
Must be set to true. false is not supported. 必须设置为true。不支持false
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.uniquetrue时,collMod扫描keyPattern索引以查找重复项,然后在没有重复索引项的情况下将其转换为唯一索引。
If duplicates are detected during the initial scan, collMod returns CannotConvertIndexToUnique 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, set prepareUnique to false.
若要将包含重复项的索引转换为唯一索引,请更正所有报告的冲突,然后重新运行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>"

Tip

See also: 另请参阅:

Validate Documents验证文档

validator

validator allows users to specify validation rules or expressions for a collection.允许用户为集合指定验证规则或表达式

The validator 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除外。

Note
  • Validation 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, and config databases.不能为admin数据库、local数据库和config数据库中的集合指定验证器。
  • You cannot specify a validator for system.* collections.不能为system.*集合指定验证器。
validationLevel

The validationLevel determines how strictly MongoDB applies the validation rules to existing documents during an update.validationLevel决定了MongoDB在更新过程中对现有文档应用验证规则的严格程度。

validationLevelDescription描述
"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

The validationAction option determines whether to error on invalid documents or just warn about the violations but allow invalid documents.validationAction选项决定是在无效文档上出错,还是只是警告违规行为,但允许无效文档。

Important

Validation 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修改视图

Note

The view modified by this command does not refer to materialized views. 此命令修改的视图不引用物化视图。For discussion of on-demand materialized views, see $merge instead.有关按需物化视图的讨论,请参阅$merge

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.定义视图聚合管道

Note

A view definition pipeline cannot include the $out or the $merge stage. 视图定义pipeline不能包含$out$merge阶段。This restriction also applies to embedded pipelines, such as pipelines used in $lookup or $facet stages.此限制也适用于嵌入式管道,例如$lookup$facet阶段中使用的管道。

Required if modifying a view on a MongoDB deployment that is running with access control.如果修改使用访问控制运行的MongoDB部署的视图,则为必需项。

The view definition is public; i.e. db.getCollectionInfos() and explain 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 the expireAfterSeconds 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 and bucketMaxSpanSeconds instead of granularity, include both custom parameters in the collMod command and set them to the same value:要更新自定义bucketRoundingSecondsbucketMaxSpanSeconds参数而不是granularity,请在collMod命令中包含这两个自定义参数,并将它们设置为相同的值:

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

You cannot decrease the granularity interval or the custom bucketing values.不能减少粒度间隔或自定义分段值。

Important

You cannot downgrade below MongoDB 6.3 if any time series collections explicitly specify the custom bucketing parameters bucketMaxSpanSeconds and bucketRoundingSeconds. 如果任何时间序列集合明确指定了自定义bucketMaxSpanSecondsbucketRoundingSeconds,则不能降级到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 granularity, value, both bucketMaxSpanSeconds and bucketRoundingSeconds must be less than or equal to the granularity equivalent:要将集合从自定义bucketing转换为granularity值,bucketMaxSpanSecondsbucketRoundingSeconds都必须小于或等于等效粒度:

granularitybucketRoundingSeconds and bucketMaxSpanSeconds limit (inclusive)限额(含)
seconds60
minutes3600
hours86400

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选项。

Note

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 than 0 and less than 1e+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 to 0 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 using db.createCollection(), create, or collMod.

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设置为trueFor example:例如:

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

To disable change stream pre- and post-images for a collection, set changeStreamPreAndPostImages to false. 要禁用集合的更改流前映像和后映像,请将changeStreamPreAndPostImages设置为falseFor 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 to 100 seconds:以下示例将expireAfterSeconds设置为100秒:

      use admin
      db.runCommand( {
      setClusterParameter:
      { changeStreamOptions: { preAndPostImages: { expireAfterSeconds: 100 } } }
      } )
    • The following example returns the current changeStreamOptions settings, including expireAfterSeconds:以下示例返回当前changeStreamOptions设置,包括expireAfterSeconds

      db.adminCommand( { getClusterParameter: "changeStreamOptions" } )
    • Setting expireAfterSeconds to off 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. A replace event always includes the post-image.不要引起replace更改事件。replace事件始终包括后映像。
  • To request a pre-image, you set fullDocumentBeforeChange to required or whenAvailable in db.collection.watch(). To request a post-image, you set fullDocument using the same method.若要请求前映像,请在db.collection.watch()中将fullDocumentBeforeChange设置为requiredwhenAvailable。若要请求后映像,请使用相同的方法设置fullDocument
  • Pre-images are written to the config.system.preimages collection.前映像将写入config.system.preimages集合。

    • The config.system.preimages collection may become large. To limit the collection size, you can set expireAfterSeconds time for the pre-images as shown earlier.config.system.preimages集合可能会变大。要限制集合大小,您可以为前映像设置expireAfterSeconds时间,如前所示。
    • Pre-images are removed asynchronously by a background process.前映像通过后台进程异步移除。
Important

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 collMod command before you can downgrade to an earlier MongoDB version.从MongoDB 6.0开始,如果您对更改流使用文档前映像和后映像,则必须使用collMod命令为每个集合禁用changeStreamPreAndPostImages,然后才能降级到早期的MongoDB版本。

Tip

See also: 另请参阅:

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:指定的注释将显示在此命令的记录旁边的以下位置:

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命令:

Task任务Required Privileges所需权限
Modify a non-capped collection修改非封顶集合collMod in the database数据库中collMod
Modify a view修改视图collMod in the database and either: 数据库中的collMod,以及以下任一个:
  • no find on the view to modify, or在要修改的视图中没有find,或者
  • both find on the view to modify and find on the source collection/view.在要修改的视图上find,在源集合/视图上find

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在查询规划器中隐藏索引

Note

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 featureCompatibilityVersion set to 4.2 on MongoDB 4.4 binaries.然而,一旦隐藏,即使在MongoDB 4.4二进制文件中将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 }
Note

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_oldhidden_new字段。

To hide a text index, you must specify the index by name and not by keyPattern.若要隐藏文本索引,必须按name而不是按keyPattern指定索引。

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.现有索引可能包含重复的条目,但当prepareUniquetrue时,它将不接受与索引条目重复的新文档。

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()