Definition定义
Changed in version 6.2.在版本6.2中的更改。
validateThevalidatecommand checks a collection's data and indexes for correctness and returns the results. The command also repairs any inconsistencies in the count and data size of a collection.validate命令检查集合的数据和索引是否正确,并返回结果。该命令还修复集合的计数和数据大小中的任何不一致。Tip
In在mongosh, this command can also be run through thevalidate()helper method.mongosh中,此命令也可以通过validate()辅助方法运行。Helper methods are convenient for助手方法对mongoshusers, 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.如果不需要便利性或需要额外的返回字段,请使用database命令。Changed in version 5.0.在版本5.0中的更改。Starting in version 5.0, the从5.0版本开始,validatecommand can also find inconsistencies in the collection and fix them if possible.validate命令还可以发现集合中的不一致,并在可能的情况下进行修复。Index inconsistencies include:指数不一致包括:An index is multikey but there are no multikey fields.索引是多键的,但没有multikey字段。An index has multikeyPaths covering fields that are not multikey.索引具有覆盖非多键字段的multikeyPaths。An index does not have multikeyPaths but there are multikey documents (for indexes built before 3.4).索引没有multikeyPaths,但有多键文档(适用于3.4之前构建的索引)。
If any inconsistencies are detected by the如果db.collection.validate()command, a warning is returned and the repair flag on the index is set totrue.db.collection.validate()命令检测到任何不一致,将返回警告,并将索引上的修复标志设置为true。db.collection.validate()also validates any documents that violate the collection's schema validation rules.还验证任何违反集合模式验证规则的文档。Note
Thevalidatecommand does not support views and raises an error when run against a view.validate命令不支持视图,并在对视图运行时引发错误。Thedb.collection.validate()method inmongoshprovides a wrapper aroundvalidate.mongosh中的db.collection.validate()方法提供了一个围绕validate的包装器。
Compatibility兼容性
This command is available in deployments hosted in the following environments:此命令在以下环境中托管的部署中可用:
- MongoDB Atlas
: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务
Important
This command is not supported in M0 and Flex clusters. For more information, see Unsupported Commands.M0和Flex集群不支持此命令。有关详细信息,请参阅不支持的命令。
- MongoDB Enterprise
: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本 - MongoDB Community
: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本
Syntax语法
The command has the following syntax:该命令具有以下语法:
db.runCommand(
{
validate: <string>, // Collection name
full: <boolean>, // Optional
repair: <boolean>, // Optional, added in MongoDB 5.0
metadata: <boolean>, // Optional, added in MongoDB 5.0.4
checkBSONConformance: <boolean> // Optional, added in MongoDB 6.2
background: <boolean> // Optional
}
)Command Fields命令字段
The command takes the following fields:该命令包含以下字段:
validate | ||
full |
| |
repair |
| |
metadata |
| |
checkBSONConformance |
| |
fixMultikey |
|
Behavior行为
Performance性能
The validate command can be slow, particularly on larger data sets.validate命令可能很慢,特别是在较大的数据集上。
The validate command obtains an exclusive lock W on the collection. validate命令获取集合上的独占锁W。This will block all reads and writes on the collection until the operation finishes. 这将阻止对集合的所有读写操作,直到操作完成。When run on a secondary, the 在辅助服务器上运行时,validate operation can block all other operations on that secondary until it finishes.validate操作可以阻止该辅助服务器上的所有其他操作,直到完成为止。
Warning
Due to the performance impact of validation, consider running 由于验证对性能的影响,请考虑仅在secondary副本集节点上运行validate only on secondary replica set nodes. You can use rs.stepDown() to instruct the current primary node to become a secondary to avoid impacting a live primary node.validate。您可以使用rs.stepDown()命令当前primary节点成为secondary,以避免影响活动的primary节点。
Data Throughput Metrics数据吞吐量指标
The $currentOp and the currentOp command include dataThroughputAverage and dataThroughputLastSecond information for validate operations in progress.$currentOp和currentOp命令包含dataThroughputAverage和dataThroughputLastSecond信息,用于验证正在进行的操作。
The log messages for validate operations include 验证操作的日志消息包括dataThroughputAverage and dataThroughputLastSecond information.dataThroughputAverage和dataThroughputLastSecond信息。
Collection Validation Improvements集合验证改进
Starting in MongoDB 6.2, the 从MongoDB 6.2开始,validate command and db.collection.validate() method:validate命令和db.collection.validate()方法:
Check collections to ensure the BSON documents conform to the BSON specifications.检查集合,确保BSON文档符合BSON规范。Check time series collections for internal data inconsistencies.检查时间序列集合是否存在内部数据不一致。Have a new option有一个新的选项checkBSONConformancethat enables comprehensive BSON checks.checkBSONConformance,可以进行全面的BSON检查。
Restrictions限制
The validate command no longer supports afterClusterTime. As such, validate cannot be associated with causally consistent sessions.validate命令在afterClusterTime之后不再支持。因此,validate不能与因果一致的会话相关联。
Time series collections were introduced in MongoDB 5.0. Starting in v5.2, the default internal format for storing time series measurements changed. Due to this change:MongoDB 5.0引入了时间序列集合。从v5.2开始,存储时间序列测量值的默认内部格式发生了变化。由于这一变化:
Time series collections created before v5.2 might contain documents in both the old and new format. Internally, such collections are flagged asv5.2之前创建的时间序列集合可能包含新旧格式的文档。在内部,这些集合被标记为timeseriesBucketsMayHaveMixedSchemaData: true.timeseriesBucketsMayHaveMixedSchemaData:true。Time series collections created in v5.2 or later will always contain documents in the new format. Internally, such collections are flagged as在v5.2或更高版本中创建的时间序列集合将始终包含新格式的文档。在内部,这样的集合被标记为时间序列timeseriesBucketsMayHaveMixedSchemaData: falseor not flagged at all.BucketsMayHaveMixedSchemaData:false或根本不标记。
When the flag is 当标志为true, time series queries take both the new and the old format into account. When the flag is false or missing, time series queries take only the new format into account.true时,时间序列查询会同时考虑新格式和旧格式。当标志为false或缺失时,时间序列查询只考虑新格式。
Due to a bug described in SERVER-91194, under some conditions the flag might be lost. When this happens for time series collections created before v5.2, read query results may be incomplete. That is, some documents may be missed, even though they are still stored on the disk.由于SERVER-91194中描述的错误,在某些情况下,标记可能会丢失。当v5.2之前创建的时间序列集合发生这种情况时,读取查询结果可能不完整。也就是说,有些文档可能会丢失,即使它们仍然存储在磁盘上。
To determine if you are impacted by this, run 要确定是否受此影响,请对时间序列集合运行validate on your time series collection. The command returns an error if the collection is affected by the bug. Your read query results may be incorrect if this is the case.validate。如果集合受错误影响,则该命令返回错误。如果是这种情况,您读取的查询结果可能不正确。
If affected, upgrade to a fixed version and set 如果受影响,请升级到固定版本,并为每个受影响的集合将timeseriesBucketsMayHaveMixedSchemaData to true for each affected collection to ensure that future queries on the collection return correct results. timeseriesBucketsMayHaveMixedSchemaData设置为true,以确保将来对该集合的查询返回正确的结果。The full steps for this process are located here.此过程的完整步骤位于此处。
Index Key Format索引键格式
Starting in MongoDB 6.0, the 从MongoDB 6.0开始,如果唯一索引的键格式不兼容,validate command returns a message if a unique index has a key format that is incompatible. The message indicates an old format is used.validate命令将返回一条消息。该消息表示使用了旧格式。
Count and Data Size Statistics计数和数据大小统计
The validate command updates the collection's count and data size statistics in the collStats output with their correct values.validate命令用正确的值更新collStats输出中的集合计数和数据大小统计信息。
Note
In the event of an unclean shutdown, the count and data size statistics might be inaccurate.如果发生不干净的关闭,计数和数据大小统计数据可能不准确。
Examples示例
To validate a collection要使用默认验证设置(特别是myCollectionusing the default validation setting (specifically, full: false):full:false)验证集合myCollection,请执行以下操作:db.runCommand( { validate: "myCollection" } )To perform a full validation of collection要对集合myCollection, specify full: true:myCollection执行完整验证,请指定full:true:db.runCommand( { validate: "myCollection", full: true } )To repair collection要修复集合myCollection, specify repair: true:myCollection,请指定repair:true:db.runCommand( { validate: "myCollection", repair: true } )To validate the metadata in the要验证myCollectioncollection, specify metadata: true:myCollection集合中的元数据,请指定metadata:true:db.runCommand( { validate: "myCollection", metadata: true } )To perform additional BSON conformance checks in要在myCollection, specify checkBSONConformance: true:myCollection中执行其他BSON一致性检查,请指定checkBSONConformance:true:db.runCommand( { validate: "myCollection", checkBSONConformance: true } )
Validate Output验证输出
Note
The output may vary depending on the version and specific configuration of your MongoDB instance.输出可能因MongoDB实例的版本和特定配置而异。
Specify full: true for more detailed output.指定full:true以获得更详细的输出。
validate.uuidThe universally unique identifier (UUID) for the collection.集合的通用唯一标识符(UUID)。New in version 6.2.在版本6.2中新增。
validate.nInvalidDocumentsThe number of invalid documents in the collection. Invalid documents are those that are not readable, which means the BSON document is corrupt and has an error or a size mismatch.集合中无效文档的数量。无效文档是指不可读的文档,这意味着BSON文档已损坏,存在错误或大小不匹配。
validate.nNonCompliantDocumentsThe number of documents not conforming to the collection's schema. Non-compliant documents are not counted as invalid in不符合集合架构的文档数。不符合要求的文档在nInvalidDocuments.nInvalidDocuments中不被视为无效。Starting in MongoDB 6.2,从MongoDB 6.2开始,nNonCompliantDocumentsalso includes the number of documents that do not conform to the BSON or time series collection requirements.nNonComplianceDocuments还包括不符合BSON或时间序列集合要求的文档数量。
validate.nrecordsThe number of documents in the collection.集合中的文档数量。
validate.nIndexesThe number of indexes on the collection that were validated.集合上已验证的索引数。
validate.keysPerIndexA document that contains the name and index entry count for each index on the collection.包含集合上每个索引的名称和索引条目计数的文档。"keysPerIndex" : {
"_id_" : <num>,
"<index2_name>" : <num>,
...
}keysPerIndexidentifies the index by its name only.仅通过索引名称标识索引。
validate.indexDetailsChanged in version 8.1.在版本8.1中的更改。A document that contains the status of the index validation for each index and the index specification.包含每个索引的索引验证状态和索引规范的文档。"indexDetails" : {
"_id_" : {
"valid" : <boolean>,
"spec" : <document>
},
"<index2_name>" : {
"valid" : <boolean>,
"spec" : <document>
},
...
}indexDetailsidentifies the specific index (or indexes) that is invalid. Earlier versions of MongoDB would mark all indexes as invalid, if any of the indexes were invalid.标识无效的特定索引。如果任何索引无效,早期版本的MongoDB会将所有索引标记为无效。indexDetailsidentifies the index by its name only. Earlier versions of MongoDB displayed the full namespace of the index; i.e.仅通过索引名称标识索引。早期版本的MongoDB显示了索引的完整命名空间;即<db>.<collection>.$<index_name>.<db>.<collection>.$<index_name>。Thespecdocument is the index specification, which varies depending on how the index is defined. Some examplespecdocument fields include:spec文档是索引规范,根据索引的定义而有所不同。一些示例spec文档字段包括:spec.v. The index version..索引版本。spec.unique. A Boolean value that indicates if the index is unique.。一个布尔值,指示索引是否唯一。spec.key. The index key identifier.索引键标识符。spec.name. The index name.。索引名称。
New in version 8.1.在版本8.1中新增。
validate.nsThe full namespace name of the collection. Namespaces include the database name and the collection name in the form集合的完整命名空间名称。命名空间包括数据库名称和表单database.collection.database.collection中的集合名称。
validate.validA boolean that is如果trueifvalidatedetermines that all aspects of the collection are valid. Whenfalse, see theerrorsfield for more information.validate确定集合的所有方面都有效,则布尔值为true。如果为false,请参阅错误字段以获取更多信息。
validate.repairedA boolean that is一个布尔值,如果trueifvalidaterepaired the collection.validate修复了集合,则为true。
validate.repairModeNew in version 8.2.在版本8.2中新增。A string that indicates what types of data inconsistencies the一个字符串,指示validatecommand attempted to repair, if detected.validate命令尝试修复哪些类型的数据不一致(如果检测到)。Possible可能的repairModevalues include:repairMode值包括:None: No repair actions are taken.:未采取任何维修行动。FixErrors: Attempts to fix any validation errors.:尝试修复任何验证错误。AdjustMultikey: Attempts to fix multikey inconsistencies by adjusting multikey metadata.:尝试通过调整多键元数据来修复多键不一致。
validate.warningsAn array that contains warning messages, if any, regarding the validate operation itself. The warning messages do not indicate that the collection is itself invalid. For example:一个数组,其中包含有关验证操作本身的警告消息(如果有的话)。警告消息并不表示集合本身无效。例如:"warnings" : [
"Could not complete validation of table:collection-28-6471619540207520785. This is a transient issue as the collection was actively in use by other operations."
],
validate.errorsIf the collection is not valid (i.e如果集合无效(即validis false), this field will contain a message describing the validation error.valid为false),则此字段将包含一条描述验证错误的消息。
validate.extraIndexEntriesAn array that contains information for each index entry that points to a document that does not exist in the collection.一个数组,包含指向集合中不存在的文档的每个索引条目的信息。"extraIndexEntries" : [
{
"indexName" : <string>,
"recordId" : <NumberLong>, // for the non-existent document
"indexKey" : {
"<key1>" : <value>,
...
}
}
...
]Note
For the对于extraIndexEntriesarray, the sum of all theindexKeyfield sizes has a limit of 1MB where the sizes include both the keys and values for theindexKey. If the sum exceeds this size, the warning field displays a message.extraIndexEntries数组,所有indexKey字段大小的总和限制为1MB,其中大小包括indexKey的键和值。如果总和超过此大小,警告字段将显示一条消息。
validate.missingIndexEntriesAn array that contains information for each document that is missing the corresponding index entry.一个数组,包含缺少相应索引条目的每个文档的信息。"missingIndexEntries" : [
{
"indexName" : <string>,
"recordId" : <NumberLong>,
"idKey" : <_id key value>, // The _id value of the document. Only present if an ``_id`` index exists.
"indexKey" : { // The missing index entry
"<key1>" : <value>,
...
}
}
...
]Note
For the对于missingIndexEntriesarray, the sum of theidKeyfield size and all itsindexKeyfield sizes has a limit of 1MB where the field sizes include both the keys and values for theidKeyandindexKey.missingIndexEntries数组,idKey字段大小与其所有indexKey字段大小之和的限制为1MB,其中字段大小包括idKey和indexKey的键和值。If the sum exceeds this size, the warning field displays a message.如果总和超过此大小,警告字段将显示一条消息。
validate.corruptRecordsAn array of不可读文档的RecordId值数组,可能是因为数据已损坏。这些文档在验证过程中被报告为已损坏。RecordIdvalues for documents that are unreadable, possibly because the data is damaged. These documents are reported as corrupt during validation.ARecordIdis a 64-bit integer internal key that uniquely identifies a document in a collection.RecordId是一个64位整数内部键,用于唯一标识集合中的文档。"corruptRecords" : [
Long(1), // RecordId 1
Long(2) // RecordId 2
]New in version 5.0.在版本5.0中新增。
validate.okAn integer with the value命令成功时,值为1when the command succeeds. If the command fails theokfield has a value of0.1的整数。如果命令失败,ok字段的值为0。