本文档适用于 mongoimport 的 100.18.0 版本。
Synopsis
mongoimport imports content from an Extended JSON, CSV, or TSV export created by mongoexport, or potentially, another third-party export tool.
Run mongoimport from the system command line, not the mongo shell.
mongoexport 提供数据导出功能。
您可以使用 Database Tools 从自托管部署迁移到 MongoDB Atlas。MongoDB Atlas 是用于云中 MongoDB 部署的完全托管服务。要了解详情,请参阅使用 mongorestore 播种。
要了解迁移到 MongoDB Atlas 的所有方法,请参阅迁移或导入数据。
提示
您还可以使用图形用户界面工具 MongoDB Compass 导入和导出数据。有关详情,请参阅 MongoDB Compass 导入和导出。
语法
mongoimport 事务语法:
mongoimport <options> <connection-string> <file>
选项
--quiet在尝试限制输出量的安静模式下运行
mongoimport。该选项会抑制:
数据库命令输出
复制活动
连接接受事件
连接关闭事件
--config=<filename>100.3.0版本新增。
指定 YAML 配置文件的完整路径,该文件包含以下
mongoimport选项的敏感值:除通过密码提示来指定密码之外,这是为
mongoimport指定密码的另一推荐方法。您可以在文件中使用任何参数的组合。配置文件采用以下形式:
password: <password> uri: mongodb://mongodb0.example.com:27017 sslPEMKeyPassword: <password> 如果您指定了
password选项但未指定uri,则可以使用mongoimport命令行选项指定连接字符串的其他组件,例如--username和--host。请务必使用相应的文件系统权限保护此文件。
重要
使用
--config选项时,请注意以下限制和行为:如果您提供
password字段,并在uri字段中提供一个与密码冲突的连接字符串,则mongorestore会抛出错误。如果您使用
--config指定配置文件,并使用--password、--uri或--sslPEMKeyPasswordmongoimport命令行选项,则命令行选项将覆盖相应的配置文件选项。
--uri=<connectionString>指定 MongoDB 部署的可解析 URI 连接字符串(用引号括起):
--uri "mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]" 注意
If you don't specify a database with the
--dbor--urioption,mongoimportuses thetestdatabase by default. If thetestdatabase doesn't exist,mongoimportcreates the database.Starting with version
100.0ofmongoimport, the connection string may alternatively be provided as a positional parameter, without using the--urioption:mongoimport mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]] 作为位置参数,可以在命令行上的任何位置指定连接字符串,前提是它以
mongodb://或mongodb+srv://开头。例如:mongoimport --username joe --password secret1 mongodb://mongodb0.example.com:27017 --ssl Only one connection string can be provided. Attempting to include more than one, whether using the
--urioption or as a positional argument, will result in an error.有关连接字符串的组件信息,请参阅连接字符串 URI 格式文档。
注意
connection string中的某些组件也可以使用各自的显式命令行选项来指定,例如--username和--password。在提供连接字符串的同时,使用显式选项并指定冲突信息会导致错误。注意
如果在Ubuntu 上使用
mongoimport18.04 ,则在使用带有 选项的cannot unmarshal DNSSRV 连接字符串(采用mongodb+srv://形式)时,您可能会遇到--uri错误消息。如果是这样,请改用以下选项之一:the
--urioption with a non-SRV connection string (in the formmongodb://)--host选项指定直接连接的主机
--host=<hostname><:port>, -h=<hostname><:port>默认:localhost:27017
指定 MongoDB 部署的可解析主机名。默认情况下,
mongoimport尝试连接到在本地主机端口号27017上运行的 MongoDB 实例。To connect to a replica set, specify the
replSetNameand a seed list of set members, as in the following:--host=<replSetName>/<hostname1><:port>,<hostname2><:port>,<...> 指定副本集列表格式时,
mongoimport始终连接到主节点。还可以通过仅指定该成员的主机和端口来连接至副本集的任何单个成员:
--host=<hostname1><:port> 如果您使用 IPv6 并采用
<address>:<port>格式,则须将地址与端口的组合部分用方括号括起(即[<address>])。或者,也可直接在
URI connection string中指定主机名。在使用--host的同时提供连接字符串并指定冲突信息将导致错误。
--port=<port>默认值:27017
指定 MongoDB 实例侦听客户端连接的 TCP 端口。
或者,也可以直接在
URI connection string中指定端口。在提供连接字符串的同时使用--port并指定冲突信息将导致错误。
--sslEnables connection to a
mongodormongosthat has TLS/SSL support enabled.或者,也可以直接在
URI connection string中配置 TLS/SSL 支持。在提供连接字符串的同时使用--ssl并指定冲突信息将导致错误。有关 TLS/SSL 和 MongoDB 的更多信息,请参阅为 TLS/SSL 配置 mongod 和 mongos 和客户端的 TLS/SSL 配置。
--sslCAFile=<filename>指定包含来自证书颁发机构的根证书链的
.pem文件。使用相对或绝对路径指定.pem文件的文件名。或者,也可以直接在
URI connection string中指定.pem文件。在提供连接字符串的同时使用--sslCAFile并指定冲突信息将导致错误。有关 TLS/SSL 和 MongoDB 的更多信息,请参阅为 TLS/SSL 配置 mongod 和 mongos 和客户端的 TLS/SSL 配置。
--sslPEMKeyFile=<filename>指定同时包含 TLS/SSL 证书和密钥的
.pem文件。使用相对或绝对路径指定.pem文件的文件名。This option is required when using the
--ssloption to connect to amongodormongosthat hasCAFileenabled withoutallowConnectionsWithoutCertificates.或者,也可以直接在
URI connection string中指定.pem文件。在提供连接字符串的同时使用--sslPEMKeyFile并指定冲突信息将导致错误。有关 TLS/SSL 和 MongoDB 的更多信息,请参阅为 TLS/SSL 配置 mongod 和 mongos 和客户端的 TLS/SSL 配置。
--sslPEMKeyPassword=<value>Specifies the password to de-crypt the certificate-key file (i.e.
--sslPEMKeyFile). Use the--sslPEMKeyPasswordoption only if the certificate-key file is encrypted. In all cases, themongoimportredacts the password from all logging and reporting output.If the private key in the PEM file is encrypted and you do not specify the
--sslPEMKeyPasswordoption, themongoimportprompts for a passphrase. See TLS/SSL Certificate Passphrase.或者,也可以直接在
URI connection string中指定密码。在提供连接字符串的同时使用--sslPEMKeyPassword并指定冲突信息将导致错误。有关 TLS/SSL 和 MongoDB 的更多信息,请参阅为 TLS/SSL 配置 mongod 和 mongos 和客户端的 TLS/SSL 配置。
警告
在某些系统上,直接使用
--sslPEMKeyPassword选项提供的密码,可能会被其他用户调用的系统状态程序(如ps)探测到。可以考虑使用--config选项,指定一个包含密码的配置文件。
--sslCRLFile=<filename>指定包含证书吊销列表的
.pem文件。使用相对或绝对路径指定.pem文件的文件名。有关 TLS/SSL 和 MongoDB 的更多信息,请参阅为 TLS/SSL 配置 mongod 和 mongos 和客户端的 TLS/SSL 配置。
--sslAllowInvalidCertificatesBypasses the validation checks for server certificates and allows the use of invalid certificates. When using the
allowInvalidCertificatessetting, MongoDB logs a warning for invalid certificates.警告
尽管可用,但请尽可能避免使用
--sslAllowInvalidCertificates选项。如果需要使用--sslAllowInvalidCertificates,请仅在不可能入侵的系统上使用该选项。Connecting to a
mongodormongosinstance without validating server certificates is a potential security risk. If you only need to disable the validation of the hostname in the TLS/SSL certificates, see--sslAllowInvalidHostnames.或者,也可以直接在
URI connection string中禁用证书验证。在提供连接字符串的同时使用--sslAllowInvalidCertificates并指定冲突信息将导致错误。有关 TLS/SSL 和 MongoDB 的更多信息,请参阅为 TLS/SSL 配置 mongod 和 mongos 和客户端的 TLS/SSL 配置。
--sslAllowInvalidHostnames禁用 TLS/SSL 证书中的主机名验证。即使证书中的主机名与指定的主机名不匹配,也支持
mongoimport连接到 MongoDB 实例。或者,也可以直接在
URI connection string中禁用主机名验证。在提供连接字符串的同时使用--sslAllowInvalidHostnames并指定冲突信息将导致错误。有关 TLS/SSL 和 MongoDB 的更多信息,请参阅为 TLS/SSL 配置 mongod 和 mongos 和客户端的 TLS/SSL 配置。
--username=<username>, -u=<username>Specifies a username with which to authenticate to a MongoDB database that uses authentication. Use in conjunction with the
--passwordand--authenticationDatabaseoptions.或者,也可直接在
URI connection string中指定用户名。在使用--username的同时提供连接字符串并指定冲突信息将导致错误。If connecting to a MongoDB Atlas cluster using the
MONGODB-AWSauthentication mechanism, you can specify your AWS access key ID in:这个字段,
the
connection string, orAWS_ACCESS_KEY_ID环境变量。
请参阅使用 AWS IAM 凭据连接到 MongoDB Atlas 集群,了解每个凭据的示例。
--password=<password>, -p=<password>Specifies a password with which to authenticate to a MongoDB database that uses authentication. Use in conjunction with the
--usernameand--authenticationDatabaseoptions.To prompt the user for the password, pass the
--usernameoption without--passwordor specify an empty string as the--passwordvalue, as in--password "".或者,也可以直接在
URI connection string中指定密码。在提供连接字符串的同时使用--password并指定冲突信息将导致错误。If connecting to a MongoDB Atlas cluster using the
MONGODB-AWSauthentication mechanism, you can specify your AWS secret access key in:这个字段,
the
connection string, orAWS_SECRET_ACCESS_KEY环境变量。
请参阅使用 AWS IAM 凭据连接到 MongoDB Atlas 集群,了解每个凭据的示例。
警告
在某些系统上,直接使用
--password选项提供的密码,可能会被其他用户调用的系统状态程序(如ps)探测到。请考虑:省略
--password选项以接收交互式密码提示,或使用
--config选项指定包含密码的配置文件。
--awsSessionToken=<AWS Session Token>If connecting to a MongoDB Atlas cluster using the
MONGODB-AWSauthentication mechanism, and using session tokens in addition to your AWS access key ID and secret access key, you can specify your AWS session token in:这个字段,
the
AWS_SESSION_TOKENauthMechanismPropertiesparameter to theconnection string, orAWS_SESSION_TOKEN环境变量。
请参阅使用 AWS IAM 凭据连接到 MongoDB Atlas 集群,了解每个凭据的示例。
仅在使用
MONGODB-AWSauthentication mechanism时有效。
--authenticationDatabase=<dbname>Specifies the authentication database where the specified
--usernamehas been created. See Authentication Database.If you use the GSSAPI (Kerberos), PLAIN (LDAP SASL), or
MONGODB-AWSauthentication mechanisms, you must set--authenticationDatabaseto$external.或者,也可以直接在
URI connection string中指定身份验证数据库。在提供连接字符串的同时使用--authenticationDatabase并指定冲突信息,将导致错误。
--authenticationMechanism=<name>默认值:SCRAM-SHA-1
Specifies the authentication mechanism the
mongoimportinstance uses to authenticate to themongodormongos.Changed in version 100.1.0:
从版本
100.1.0开始,mongoimport添加了在连接 MongoDB Atlas 集群时对MONGODB-AWS身份验证机制的支持。值说明5802使用 SHA-1 哈希函数的 RFC 标准 Salted 挑战响应身份验证机制。
RFC 7677 standard Salted Challenge Response Authentication Mechanism using the SHA-256 hash function.
需将 featureCompatibilityVersion 设为
4.0。MongoDB TLS/SSL 证书身份验证。
MONGODB-AWS使用 AWS IAM 凭据进行外部身份验证,用于连接到 MongoDB Atlas 集群。请参阅使用 AWS IAM 凭证连接到 MongoDB Atlas 集群。
100.1.0版本新增。
GSSAPI (Kerberos)
使用 Kerberos 的外部身份验证。此机制仅在 MongoDB Enterprise 中可用。
普通版 (LDAP SASL)
使用 LDAP 进行外部身份验证。您也可使用
PLAIN对数据库内用户进行身份验证。PLAIN以纯文本形式传输密码。此机制仅在 MongoDB Enterprise 中可用。或者,也可以直接在
URI connection string中指定身份验证机制。在提供连接字符串的同时使用--authenticationMechanism并指定冲突信息,将导致错误。
--gssapiServiceName=<serviceName>Specify the name of the service using GSSAPI/Kerberos. Only required if the service does not use the default name of
mongodb.此选项仅在 MongoDB Enterprise 中可用。
--gssapiHostName=<hostname>使用 GSSAPI/Kerberos 指定服务的主机名。仅当机器的主机名与 DNS 解析的主机名不匹配时才需要。
此选项仅在 MongoDB Enterprise 中可用。
--db=<database>, -d=<database>指定要在其上运行
mongoimport的数据库的名称。或者也可以直接在
URI connection string中指定数据库。在提供连接字符串的同时使用--db并指定冲突信息将导致错误。
--collection=<collection>, -c=<collection>Specifies the collection to import. If you do not specify
--collection,mongoimportreads the collection name from the input filename, omitting the file's extension if it has one.
--fields=<field1[,field2]>, -f=<field1[,field2]>导入 CSV 或 TSV 文件时,如果文件第一行(即页眉)中没有字段名称,请指定一个以逗号分隔的字段名称列表。
To also specify the field type as well as the field name, use
--fieldswith--columnsHaveTypes.If you attempt to include
--fieldswhen importing JSON data,mongoimportreturns an error.--fieldsis only for CSV or TSV imports.
--fieldFile=<filename>As an alternative to
--fields, the--fieldFileoption allows you to specify a file that holds a list of field names if your CSV or TSV file does not include field names in the first line of the file (i.e. header). Place one field per line.To also specify the field type as well as the field name, use
--fieldFilewith--columnsHaveTypes.If you attempt to include
--fieldFilewhen importing JSON data,mongoimportreturns an error.--fieldFileis only for CSV or TSV imports.
--ignoreBlanksIgnores empty fields in CSV and TSV exports. If not specified,
mongoimportcreates fields without values in imported documents.If you attempt to include
--ignoreBlankswhen importing JSON data,mongoimportreturns an error.--ignoreBlanksis only for CSV or TSV imports.
--type=<json|csv|tsv>指定要导入的文件类型。默认格式为 JSON,但可以导入 CSV 和 TSV 文件。
csv解析器接受符合 RFC-4180 的数据。因此,反斜杠不是有效的转义字符。如果使用双引号将逗号分隔值(CSV)数据中的字段括起来,则必须通过在前面添加另一个双引号来转义内部双引号。
--drop修改导入过程,以便目标实例在从输入导入数据之前删除集合和任何关联的索引。
--headerlineIf using
--type csvor--type tsv, uses the first line as field names. Otherwise,mongoimportimports the first line as a distinct document.If you attempt to include
--headerlinewhen importing JSON data,mongoimportreturns an error.--headerlineis only for CSV or TSV imports.
--useArrayIndexFields100.0.0版本新增。
导入 CSV 或 TSV 文件时,将字段中的自然数解释为数组索引。
字段名称必须采用
<colName>.<arrayIndex>形式,其中arrayIndex是一个自然数,从0开始,依次递增1,数组中的每个成员都是如此。例如,使用以下 CSV 文件:
a.0,a.1,a.2,a.3 red,yellow,green,blue An import with the
--useArrayIndexFieldsoption would result in the following document:"a" : [ "red", "yellow", "green", "blue" ] If using the
--columnsHaveTypesoption as well, use the form<colName>.<arrayIndex>.<type>(<arg>)to specify both the array index and type for each field. See--columnsHaveTypesfor more information.带有前导零的数字键(例如
a.000,a.001) 不会被解释为数组索引。如果键的第一部分是自然数(例如
0.a,1.a),会被解释为文档键,而不是数组索引。If using the
--ignoreBlanksoption with--useArrayIndexFields,mongoimportreturns an error if you attempt to import a document that contains a blank value (e.g."") for an array index field.The
--useArrayIndexFieldsoption has no effect when importing JSON data, as arrays are already encoded in JSON format.
--mode=<insert|upsert|merge|delete>Default: insert
指定导入进程应如何处理数据库中与导入文件中的文档相匹配的现有文档。
By default,
mongoimportuses the_idfield to match documents in the collection with documents in the import file. To specify the fields against which to match existing documents for theupsert,merge, anddeletemodes, use--upsertFields.值说明insertInsert the documents in the import file.
mongoimportreturns an error if you attempt to import a document that contains a duplicate value for a field with a unique index, such as_id.upsertReplace existing documents in the database with matching documents from the import file.
mongoimportinserts all other documents. Replace Matching Documents during Import describes how to use--modeupsert.mergeMerge existing documents that match a document in the import file with the new document.
mongoimportinserts all other documents. Merge Matching Documents during Import describes how to use--modemerge.deleteDelete existing documents in the database that match a document in the import file.
mongoimporttakes no action on non-matching documents. Delete Matching Documents describes how to use--modedelete.100.0.0版本新增。
--upsertFields=<field1[,field2]>Specifies a list of fields for the query portion of the import process.
--upsertFieldscan be used with--modeupsert,merge, anddelete.如果现有文档中的
_id字段与文档中的字段不匹配,但其他字段或字段组合可以唯一地标识文档,作为执行更新或插入操作的基础,则使用此选项。If you do not specify a field,
--upsertFieldsupserts on the basis of the_idfield.To ensure adequate performance, indexes should exist for the field or fields you specify with
--upsertFields.
--stopOnError强制
mongoimport在出现第一个错误时停止插入操作,而不是出错时继续执行此操作。By default,
mongoimportcontinues an operation when it encounters duplicate key and document validation errors. To ensure that the program stops on these errors, specify--stopOnError.
--jsonArray接受在单个JSON大量中导入用多个MongoDB文档表示的数据。仅限于 16MB 或更小的导入。
Use
--jsonArrayin conjunction withmongoexport --jsonArray.
--legacy表示导入数据采用扩展JSON v1 格式,而不是默认的扩展JSON v2 格式。
提示
一般来说,
mongoexport和mongoimport的版本应该匹配。 也就是说,要导入从mongoexport创建的数据,应使用相应版本的mongoimport。例如,如果导入数据是 v1 格式:
{"_id":1.0,"myregfield":{"$regex":"foo","$options":"i"}} Import without the
--legacyoption results in the following document in the collection:{ "_id" : 1, "myregfield" : { "$regex" : "foo", "$options" : "i" } } Import with the
--legacyresults in the following document in the collection:{ "_id" : 1, "myregfield" : { "$regularExpression" : { "pattern" : "foo", "options" : "i" } } }
--maintainInsertionOrder默认:false
如果已指定,
mongoimport则会按照这些文档在输入源中出现的顺序将其插入。也就是说,批量写入批处理顺序和批处理中的文档顺序都将保持不变。指定
--maintainInsertionOrder还会启用--stopOnError并将numInsertionWorkers设置为1 。如果未指定,
mongoimport则可能会按任意顺序执行插入。
--writeConcern=<document>默认:多数
Specifies the write concern for each write operation that
mongoimportperforms.将写关注指定为文档,并使用 w 选项:
--writeConcern "{w:'majority'}" If the write concern is also included in the
--uri connection string, the command-line--writeConcernoverrides the write concern specified in the URI string.
--bypassDocumentValidation启用
mongoimport以便在操作过程中绕过文档验证。这样就可以插入不符合验证要求的文档。
--columnsHaveTypesInstructs
mongoimportthat the field list specified in--fields,--fieldFile, or--headerlinespecifies the types of each field.字段名称必须采用
<colName>.<type>(<arg>)的格式。如果要将以下字符包含在参数中,则必须进行反斜杠转义:(、)和\。type支持的参数示例头字段auto()无。
misc.auto()binary(<arg>)user thumbnail.binary(base64)boolean()无。
verified.boolean()date(<arg>)date_go(<arg>)的别名。Go 语言 time.Parse 格式。created.date(2006-01-02 15:04:05)date_go(<arg>)created.date_go(2006-01-02T15:04:05Z)date_ms(<arg>)created.date_ms(yyyy-MM-dd H:mm:ss)date_oracle(<arg>)created.date_oracle(YYYY-MM-DD HH24:MI:SS)decimal()无
price.decimal()double()无。
revenue.double()int32()无。
followerCount.int32()int64()无。
bigNumber.int64()string()无。
zipcode.string()有关示例用法,请参阅导入具有指定字段类型的 CSV 。
If you attempt to include
--columnsHaveTypeswhen importing JSON data,mongoimportreturns an error.--columnsHaveTypesis only for CSV or TSV imports.
--parseGrace=<grace>默认值:stop(停止)
Specifies how
mongoimporthandles type coercion failures when importing CSV or TSV files with--columnsHaveTypes.--parseGrace导入 JSON 文档时无效。值说明autoCast根据字段值指定类型。 例如,如果一个字段定义为
double,而该字段的值为"foo",则mongoimport将使该字段值成为string类型。skipField对于正在导入的行,
mongoimport不包括类型与预期类型不匹配的字段。skipRowmongoimport不会导入包含其类型与所需类型 不匹配的值的对应行。stopmongoimport返回一个错误,将会结束导入。