mongoimport
macOS Sierra and Go 1.6 Incompatibility
Users running on macOS Sierra require the 3.2.10 or newer versionof mongoimport.
Synopsis
The mongoimport
tool imports content from anExtended JSON, CSV, or TSV exportcreated by mongoexport
, or potentially, another third-party exporttool.
See the mongoexport document for more information regardingmongoexport
, which provides the inverse “exporting”capability.
Run mongoimport
from the system command line, not the mongo
shell.
Availability
The mongoimport
tool is part of the MongoDB tools package. Consult theinstallation guide for your platform forinstructions on how to install the tools package as part of yourMongoDB installation.
The tools package is also available from theMongoDB Download Center,either as a separate tools
download, or contained within theTGZ
or ZIP
downloads, depending on platform. On Windows, the MSI
installer includes all tools as part of the default installation.
Tip
If downloading the TGZ
or ZIP
files from the DownloadCenter, you may want to update your PATH
environmentvariable to include the directory where you installed these tools.See the installation guidefor your platform for more information.
Behavior
Warning
Avoid using mongoimport
and mongoexport
forfull instance production backups. They do not reliably preserve all richBSON data types, because JSON can only represent a subsetof the types supported by BSON. Use mongodump
and mongorestore
as described in MongoDB Backup Methods for thiskind of functionality.
JSON Format
Starting in MongoDB 4.2, mongoimport
expects import datato be in Extended JSON v2.0 (either Relaxed or Canonical mode)by default. To recognize data that is in Extended JSON v1.0 format, see—legacy
.
In earlier versions, mongoimport
expects data inMongoDB Extended JSON (v1) format.
Tip
In general, the versions of mongoexport
andmongoimport
should match. That is, to import datacreated from mongoexport
, you should use thecorresponding version of mongoimport
.
Encoding
mongoimport
only supports data files that are UTF-8 encoded.Using other encodings will produce errors.
FIPS
Starting in version 4.2, MongoDB removes the —sslFIPSMode
option for mongoimport. mongoimportwill use FIPS compliant connections tomongod
/mongos
if themongod
/mongos
instances areconfigured to use FIPS mode.
Write Concern
Starting in version 4.2, if you specify write concern in both the—writeConcern
option and the—uri connection string
option, the—writeConcern
value overridesthe write concern specified in the URI string.
In earlier versions, the two options are incompatible.
Batches
Starting in MongoDB 4.2, mongoimport
uses maximum batchsize of 100,000 to perform bulk insert/upsert operations.
Required Access
In order to connect to a mongod
that enforces authorizationwith the —auth
option, you must use the—username
and —password
options. The connecting user mustpossess, at a minimum, the readWrite
role on the databaseinto which they are importing data.
Options
Changed in version 3.0.0: mongoimport
removed the —dbpath
as well as related—directoryperdb
and —journal
options. To usemongoimport
, you must run mongoimport
against a runningmongod
or mongos
instance as appropriate.
—verbose
,
-v
- Increases the amount of internal reporting returned on standard outputor in log files. Increase the verbosity with the
-v
form byincluding the option multiple times, (e.g.-vvvvv
.)
This option suppresses:
- output from database commands
- replication activity
- connection accepted events
- connection closed events
New in version 3.4.6.
Specify a resolvable URIconnection string (enclose in quotes) to connect to the MongoDB deployment.
- --uri "mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]"
For information on the components of the connection string, seethe Connection String URI Format documentation.
Note
For TLS/SSL options, use the command-line options instead of theURI options for TLS/SSL (Available starting in4.2).
Important
The following command-line options cannot be used in conjunctionwith —uri
option:
—host
—port
—db
—username
—password
(if theURI connection string also includes the password)—authenticationDatabase
—authenticationMechanism
Instead, specify these options as part of your—uri
connection string.
Specifies a resolvable hostname for the mongod
to which toconnect. By default, the mongoimport attempts to connect to a MongoDBinstance running on the localhost on port number 27017
.
To connect to a replica set, specify thereplSetName
and a seed list of set members, as inthe following:
- --host=<replSetName>/<hostname1><:port>,<hostname2><:port>,<...>
When specifying the replica set list format, mongoimport always connects tothe primary.
You can also connect to any single member of the replica set by specifyingthe host and port of only that member:
- --host=<hostname1><:port>
Changed in version 3.0.0: If you use IPv6 and use the <address>:<port>
format, you mustenclose the portion of an address and port combination inbrackets (e.g. [<address>]
).
Note
You cannot specify both —host
and —uri
.
Specifies the TCP port on which the MongoDB instance listens forclient connections.
Note
You cannot specify both —port
and —uri
.
Enables IPv6 support and allows mongoimport to connect to theMongoDB instance using an IPv6 network. Prior to MongoDB 3.0, youhad to specify —ipv6
to use IPv6. In MongoDB 3.0 and later, IPv6is always enabled.
New in version 2.6.
Enables connection to a mongod
or mongos
that hasTLS/SSL support enabled.
For more information about TLS/SSL and MongoDB, seeConfigure mongod and mongos for TLS/SSL andTLS/SSL Configuration for Clients .
New in version 2.6.
Specifies the .pem
file that contains the root certificate chainfrom the Certificate Authority. Specify the file name of the.pem
file using relative or absolute paths.
Starting in version 3.4, if —tlsCAFile
/net.tls.CAFile
(ortheir aliases —sslCAFile
/net.ssl.CAFile
) is not specifiedand you are not using x.509 authentication, the system-wide CAcertificate store will be used when connecting to an TLS/SSL-enabledserver.
To use x.509 authentication, —tlsCAFile
or net.tls.CAFile
must be specified unless using —tlsCertificateSelector
or—net.tls.certificateSelector
. Or if using the ssl
aliases,—sslCAFile
or net.ssl.CAFile
must be specified unless using—sslCertificateSelector
or net.ssl.certificateSelector
.
Warning
Version 3.2 and earlier: For TLS/SSL connections (—ssl
) tomongod
and mongos
, if the mongoimport runs without the—sslCAFile
, mongoimport will not attemptto validate the server certificates. This creates a vulnerabilityto expired mongod
and mongos
certificates aswell as to foreign processes posing as valid mongod
ormongos
instances. Ensure that you always specify theCA file to validate the server certificates in cases whereintrusion is a possibility.
For more information about TLS/SSL and MongoDB, seeConfigure mongod and mongos for TLS/SSL andTLS/SSL Configuration for Clients .
New in version 2.6.
Specifies the .pem
file that contains both the TLS/SSL certificateand key. Specify the file name of the .pem
file using relativeor absolute paths.
This option is required when using the —ssl
option to connectto a mongod
or mongos
that hasCAFile
enabled withoutallowConnectionsWithoutCertificates
.
For more information about TLS/SSL and MongoDB, seeConfigure mongod and mongos for TLS/SSL andTLS/SSL Configuration for Clients .
New in version 2.6.
Specifies the password to de-crypt the certificate-key file (i.e.—sslPEMKeyFile
). Use the —sslPEMKeyPassword
option only if thecertificate-key file is encrypted. In all cases, the mongoimport willredact the password from all logging and reporting output.
If the private key in the PEM file is encrypted and you do not specifythe —sslPEMKeyPassword
option, the mongoimport will prompt for a passphrase. SeeTLS/SSL Certificate Passphrase.
For more information about TLS/SSL and MongoDB, seeConfigure mongod and mongos for TLS/SSL andTLS/SSL Configuration for Clients .
New in version 2.6.
Specifies the .pem
file that contains the Certificate RevocationList. Specify the file name of the .pem
file using relative orabsolute paths.
For more information about TLS/SSL and MongoDB, seeConfigure mongod and mongos for TLS/SSL andTLS/SSL Configuration for Clients .
New in version 2.6.
Bypasses the validation checks for server certificates and allowsthe use of invalid certificates. When using theallowInvalidCertificates
setting, MongoDB logs as awarning the use of the invalid certificate.
Starting in MongoDB 4.0, if you specify—sslAllowInvalidCertificates
ornet.ssl.allowInvalidCertificates: true
(or in MongoDB 4.2, thealias —tlsAllowInvalidateCertificates
ornet.tls.allowInvalidCertificates: true
) when using x.509authentication, an invalid certificate is only sufficient toestablish a TLS/SSL connection but is insufficient forauthentication.
Warning
Although available, avoid using the—sslAllowInvalidCertificates
option if possible. If the use of—sslAllowInvalidCertificates
is necessary, only use the optionon systems where intrusion is not possible.
If the mongo
shell (and otherMongoDB Tools) runs with the—sslAllowInvalidCertificates
option, themongo
shell (and otherMongoDB Tools) will not attempt to validatethe server certificates. This creates a vulnerability to expiredmongod
and mongos
certificates aswell as to foreign processes posing as validmongod
or mongos
instances. If youonly need to disable the validation of the hostname in theTLS/SSL certificates, see —sslAllowInvalidHostnames
.
For more information about TLS/SSL and MongoDB, seeConfigure mongod and mongos for TLS/SSL andTLS/SSL Configuration for Clients .
New in version 3.0.
Disables the validation of the hostnames in TLS/SSL certificates. Allowsmongoimport to connect to MongoDB instances even if the hostname in theircertificates do not match the specified hostname.
For more information about TLS/SSL and MongoDB, seeConfigure mongod and mongos for TLS/SSL andTLS/SSL Configuration for Clients .
—username
=<username>
,
-u
=<username>
- Specifies a username with which to authenticate to a MongoDB databasethat uses authentication. Use in conjunction with the
—password
and—authenticationDatabase
options.
Note
You cannot specify both —username
and —uri
.
—password
=<password>
,
-p
=<password>
- Specifies a password with which to authenticate to a MongoDB databasethat uses authentication. Use in conjunction with the
—username
and—authenticationDatabase
options.
Changed in version 3.0.2: To prompt the userfor the password, pass the —username
option without—password
or specify an empty string as the —password
value,as in —password ""
.
Note
You cannot specify both —password
and —uri
.
—authenticationDatabase
=<dbname>
- Specifies the authentication database where the specified
—username
has been created.See Authentication Database.
Note
You cannot specify both —authenticationDatabase
and —uri
.
Specifies the authentication mechanism the mongoimport instance uses toauthenticate to the mongod
or mongos
.
Changed in version 4.0: MongoDB removes support for the deprecated MongoDBChallenge-Response (MONGODB-CR
) authentication mechanism.
MongoDB adds support for SCRAM mechanism using the SHA-256 hashfunction (SCRAM-SHA-256
).
ValueDescriptionSCRAM-SHA-1RFC 5802 standardSalted Challenge Response Authentication Mechanism using the SHA-1hash function.SCRAM-SHA-256RFC 7677 standardSalted Challenge Response Authentication Mechanism using the SHA-256hash function.
Requires featureCompatibilityVersion set to 4.0
.
New in version 4.0.
MONGODB-X509MongoDB TLS/SSL certificate authentication.GSSAPI (Kerberos)External authentication using Kerberos. This mechanism isavailable only in MongoDB Enterprise.PLAIN (LDAP SASL)External authentication using LDAP. You can also use PLAIN
for authenticating in-database users. PLAIN
transmitspasswords in plain text. This mechanism is available only inMongoDB Enterprise.
Note
You cannot specify both —authenticationMechanism
and —uri
.
New in version 2.6.
Specify the name of the service using GSSAPI/Kerberos. Only required if the service does not use thedefault name of mongodb
.
This option is available only in MongoDB Enterprise.
New in version 2.6.
Specify the hostname of a service using GSSAPI/Kerberos. Only required if the hostname of a machine doesnot match the hostname resolved by DNS.
This option is available only in MongoDB Enterprise.
Note
You cannot specify both —db
and —uri
.
New in version 2.6: If you do not specify —collection
,mongoimport
takes the collection name from the inputfilename. MongoDB omits the extension of the file from thecollection name, if the input file has an extension.
—fields
=<field1[,field2]>
,
-f
=<field1[,field2]>
- Specify a comma separated list of field names when importing csvor tsv files that do not have field names in the first (i.e.header) line of the file.
To also specify the field type as well as the field name, use—fields
with —columnsHaveTypes
.
If you attempt to include —fields
when importing JSON data,mongoimport will return an error. —fields
is only for csvor tsv imports.
—fieldFile
=<filename>
- As an alternative to
—fields
, the—fieldFile
option allows you to specify a file that holds a list of field names ifyour csv or tsv file does not include field names in thefirst 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—fieldFile
with —columnsHaveTypes
.
If you attempt to include —fieldFile
when importing JSON data,mongoimport will return an error. —fieldFile
is only for csvor tsv imports.
—ignoreBlanks
- Ignores empty fields in csv and tsv exports. If notspecified,
mongoimport
creates fields without values inimported documents.
If you attempt to include —ignoreBlanks
when importing JSON data,mongoimport will return an error. —ignoreBlanks
is only for csvor tsv imports.
—type
=<json|csv|tsv>
- Specifies the file type to import. The default format is JSON,but it’s possible to import csv and tsv files.
The csv
parser accepts that data that complies with RFCRFC 4180. As a result, backslashes are not a valid escapecharacter. If you use double-quotes to enclose fields in the CSVdata, you must escape internal double-quote marks by prependinganother double-quote.
—file
=<filename>
- Specifies the location and name of a file containing the data to import.If you do not specify a file,
mongoimport
reads data fromstandard input (e.g. “stdin”).
—drop
- Modifies the import process so that the target instance dropsthe collection before importing the data from the input.
—headerline
- If using
—type csv
or—typetsv
, uses the first line as field names.Otherwise,mongoimport
will import the first line as adistinct document.
If you attempt to include —headerline
when importing JSON data,mongoimport will return an error. —headerline
is only for csvor tsv imports.
New in version 3.4.
Specifies how the import process should handle existing documentsin the database that match documents in the import file.
By default, mongoimport uses the _id
field to match documents inthe collection with documents in the import file.To specify the fields against which to match existingdocuments for the upsert
and merge
modes,use —upsertFields
.
ValueDescriptioninsert
Insert the documents in the import file. mongoimport will logan error if you attempt to import a document that contains aduplicate value for a field with a unique index, such as _id
.upsert
Replace existing documents in the database with matchingdocuments from theimport file. mongoimport will insert all otherdocuments. Replace Matching Documents during Import describes how touse —mode
upsert
.merge
Merge existing documents that match a document in the import file withthe new document. mongoimport will insert all other documents.Merge Matching Documents during Import describes how to use —mode
merge
.
—upsertFields
=<field1[,field2]>
- Specifies a list of fields for the query portion of theupsert.Use this option if the
_id
fields in theexisting documents don’t match the field in the document, butanother field or field combination can uniquely identifydocuments as a basis for performing upsert operations.
Changed in version 3.4: Modifies the import process to update existing objects in thedatabase if they match based on the specified fields, whileinserting all other objects. You do not need to use —modeupsert
with —upsertFields
.
If you do not specify a field, —upsertFields
will upsert on the basis ofthe _id
field.
To ensure adequate performance, indexes should exist for thisfield or fields.
—stopOnError
- Forces mongoimport to halt the insert operation at thefirst error rather than continuing the operation despite errors.
Starting in version 4.2, mongoimport
, by default,continues when it encounters duplicate key and documentvalidation errors. To ensure that the program stops on these errors, specify —stopOnError
.
—jsonArray
- Accepts the import of data expressed with multiple MongoDB documentswithin a single JSON array. Limited toimports of 16 MB or smaller.
Use —jsonArray
in conjunction with mongoexport —jsonArray
.
—legacy
- Indicates that the import data is in Extended JSON v1 format instead of the defaultExtended JSON v2 format.
Tip
In general, the versions of mongoexport
andmongoimport
should match. That is, to importdata created from mongoexport
, you should usethe corresponding version of mongoimport
.
For example, if the import data is in v1 format:
- {"_id":1.0,"myregfield":{"$regex":"foo","$options":"i"}}
Import without the —legacy
option results inthe following document in the collection:
- { "_id" : 1, "myregfield" : { "$regex" : "foo", "$options" : "i" } }
Import with the —legacy
results inthe following document in the collection:
- { "_id" : 1, "myregfield" : { "$regularExpression" : { "pattern" : "foo", "options" : "i" } } }
New in version 4.2.
If specified,
- Starting in version 4.2, mongoimport inserts thedocuments in the order of their appearance in the input source. Thatis, both the bulk write batch order and document order within thebatches are maintained.
- In earlier versions, only the batch order is maintained; documentorder within batches are not maintained.Starting in MongoDB 4.2, specifying
—maintainInsertionOrder
also enables—stopOnError
and setsnumInsertionWorkers
to 1.
If unspecified, mongoimport may perform the insertions in anarbitrary order.
New in version 3.0.0.
Specifies the number of insertion workers to run concurrently.
For large imports, increasing the number of insertion workersmay increase the speed of the import.
Specifies the write concern for each write operation that mongoimportperforms.
Specify the write concern as a document with w options:
- --writeConcern "{w:'majority'}"
If the write concern is also included in the —uriconnection string
, the command-line—writeConcern
overrides the write concern specified inthe URI string.
—bypassDocumentValidation
- Enables mongoimport to bypass document validationduring the operation. This lets you insert documents that do notmeet the validation requirements.
New in version 3.2.1.
New in version 3.4.
Instructs mongoimport that thefield list specified in —fields
, —fieldFile
,or —headerline
specifies the types of each field.
Field names must be in the form of <colName>.<type>(<arg>)
. Youmust backslash-escape the following characters if you wish to includethem in an argument: (
, )
, and \
.
type
Supported ArgumentsExample Header Fieldauto()
None.misc.auto()
binary(<arg>)
base32
(RFC4648 encoding schema)base64
(RFC4648 encoding schema)hex
user thumbnail.binary(base64)
boolean()
None.verified.boolean()
date(<arg>)
Alias fordate_go(<arg>)
. Go Language time.Parse format.created.date(2006-01-02 15:04:05)
date_go(<arg>)
Go Language time.Parse formatcreated.date_go(2006-01-02 15:04:05)
date_ms(<arg>)
Microsoft SQL Server FORMAT formatcreated.date_ms(yyyy-MM-dd H:mm:ss)
date_oracle(<arg>)
Oracle Database TO_DATE format.created.date_oracle(YYYY-MM-DD HH24:MI:SS)
decimal()
Noneprice.decimal()
double()
None.revenue.double()
int32()
None.followerCount.int32()
int64()
None.bigNumber.int64()
string()
None.zipcode.string()
See Import CSV with Specified Field Types for sample usage.
If you attempt to include —columnsHaveTypes
when importing JSON data,mongoimport will return an error. —columnsHaveTypes
is only for csvor tsv imports.
New in version 3.4.
Specifies how mongoimport handles type coercion failures when importingCSV or TSV files with —columnsHaveTypes
.
—parseGrace
has no effect when importing JSON documents.
ValueDescriptionautoCast
Assigns a type based on the value of the field.For example, if a field is defined as a double
and thevalue for that field was "foo"
, mongoimport would makethat field value a string type.skipField
For the row being imported, mongoimport does not include thefield whose type does not match the expected type.skipRow
mongoimport does not import rows containing a value whosetype does not match the expected type.stop
mongoimport returns an error that ends the import.
Examples
Simple Import
mongoimport
restores a database from a backup taken withmongoexport
. Most of the arguments to mongoexport
alsoexist for mongoimport
.
In the following example, mongoimport
importsthe JSON data from the contacts.json
file into the collectioncontacts
in the users
database.
- mongoimport --db=users --collection=contacts --file=contacts.json
Replace Matching Documents during Import
Changed in version 3.4: In MongoDB 3.4, —mode upsert
replaces thedeprecated —upsert
option.
With —mode
upsert
, mongoimport
replacesexisting documents in the database that match a document in theimport file with the document from the import file.Documents that do not match an existing document in the database areinserted as usual. By default mongoimport
matches documentsbased on the _id
field. Use —upsertFields
to specifythe fields to match against.
Consider the following document in the people
collection in theexample
database:
- {
- "_id" : ObjectId("580100f4da893943d393e909"),
- "name" : "Crystal Duncan",
- "region" : "United States",
- "email" : "crystal@example.com"
- }
The following document exists in a people-20160927.json
JSON file.The _id
field of the JSON object matches the _id
field of thedocument in the people
collection.
- {
- "_id" : ObjectId("580100f4da893943d393e909"),
- "username" : "crystal",
- "likes" : [ "running", "pandas", "software development" ]
- }
To import the people-20160927.json
file and replace documents inthe database that match the documents in the import file, specify —mode
upsert
, as in the following:
- mongoimport -c=people -d=example --mode=upsert --file=people-20160927.json
The document in the people
collection would then contain onlythe fields from the imported document, as in the following:
- {
- "_id" : ObjectId("580100f4da893943d393e909"),
- "username" : "crystal",
- "likes" : [ "running", "pandas", "software development" ]
- }
Merge Matching Documents during Import
New in version 3.4.
With —mode
merge
, mongoimport
enables you tomerge fields from a new record with an existing document in thedatabase. Documents that do not match an existing document in thedatabase are inserted as usual. By default mongoimport
matches documents based on the _id
field. Use—upsertFields
to specify the fields to match against.
The people
collection in the example
database contains thefollowing document:
- {
- "_id" : ObjectId("580100f4da893943d393e909"),
- "name" : "Crystal Duncan",
- "region" : "United States",
- "email" : "crystal@example.com"
- }
The following document exists in a people-20160927.json
JSON file.The _id
field of the JSON object matches the _id
field of thedocument in the people
collection.
- {
- "_id" : ObjectId("580100f4da893943d393e909"),
- "username" : "crystal",
- "email": "crystal.duncan@example.com",
- "likes" : [ "running", "pandas", "software development" ]
- }
To import the people-20160927.json
file and merge documents fromthe import file with matching documents in the database, specify—mode
merge
, as in the following:
- mongoimport -c=people -d=example --mode=merge --file=people-20160927.json
The import operation combines the fields from the JSON file with theoriginal document in the database,matching the documents based on the _id
field.During the import process, mongoimport
adds the new username
andlikes
fields to the document and updates the email
field withthe value from the imported document, as in the following:
- {
- "_id" : ObjectId("580100f4da893943d393e909"),
- "name" : "Crystal Duncan",
- "region" : "United States",
- "email" : "crystal.duncan@example.com",
- "username" : "crystal",
- "likes" : [
- "running",
- "pandas",
- "software development"
- ]
- }
Import JSON to Remote Host Running with Authentication
In the following example, mongoimport
imports data from thefile /opt/backups/mdb1-examplenet.json
into the contacts
collectionwithin the database marketing
on a remote MongoDBdatabase with authentication enabled.
mongoimport
connects to the mongod
instance running onthe host mongodb1.example.net
over port 37017
. It authenticates with theusername user
; the example omits the —password
option to have mongoimport
prompt for the password:
- mongoimport --host=mongodb1.example.net --port=37017 --username=user --collection=contacts --db=marketing --file=/opt/backups/mdb1-examplenet.json
CSV Import
General CSV Import
In the following example, mongoimport
imports the csvformatted data in the /opt/backups/contacts.csv
file into thecollection contacts
in the users
database on the MongoDBinstance running on the localhost port numbered27017
.
Specifying —headerline
instructsmongoimport
to determine the name of the fields using the firstline in the CSV file.
- mongoimport --db=users --collection=contacts --type=csv --headerline --file=/opt/backups/contacts.csv
mongoimport
uses the input file name, without theextension, as the collection name if -c
or —collection
isunspecified. The following example is therefore equivalent:
- mongoimport --db=users --type=csv --headerline --file=/opt/backups/contacts.csv
Import CSV with Specified Field Types
New in version 3.4.
Starting in MongoDB 3.4, when you specify the field name, you can alsospecify the data type. To specify field names and type, include—columnsHaveTypes
witheither: —fields
, —fieldFile
, or —headerline
.
Specify field names and data types in the form<colName>.<type>(<arg>)
.
For example, a /example/file.csv
file contains the following data:
- Katherine Gray, 1996-02-03, false, 1235, TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdCwgc2VkIGRvIGVpdXNtb2QgdGVtcG9yIGluY2lkaWR1bnQgdXQgbGFib3JlIGV0IGRvbG9yZSBtYWduYSBhbGlxdWEuIFV0IGVuaW0gYWQgbWluaW0gdmVuaWFtLCBxdWlzIG5vc3RydWQgZXhlcmNpdGF0aW9uIHVsbGFtY28gbGFib3JpcyBuaXNpIHV0IGFsaXF1aXAgZXggZWEgY29tbW9kbyBjb25zZXF1YXQuIER1aXMgYXV0ZSBpcnVyZSBkb2xvciBpbiByZXByZWhlbmRlcml0IGluIHZvbHVwdGF0ZSB2ZWxpdCBlc3NlIGNpbGx1bSBkb2xvcmUgZXUgZnVnaWF0IG51bGxhIHBhcmlhdHVyLiBFeGNlcHRldXIgc2ludCBvY2NhZWNhdCBjdXBpZGF0YXQgbm9uIHByb2lkZW50LCBzdW50IGluIGN1bHBhIHF1aSBvZmZpY2lhIGRlc2VydW50IG1vbGxpdCBhbmltIGlkIGVzdCBsYWJvcnVtLg==
- Albert Gilbert, 1992-04-24, true, 13, Q3VwY2FrZSBpcHN1bSBkb2xvciBzaXQgYW1ldCB0b290c2llIHJvbGwgYm9uYm9uIHRvZmZlZS4gQ2FuZHkgY2FuZXMgcGllIGNyb2lzc2FudCBjaG9jb2xhdGUgYmFyIGxvbGxpcG9wIGJlYXIgY2xhdyBtYWNhcm9vbi4gU3dlZXQgcm9sbCBjdXBjYWtlIGNoZWVzZWNha2Ugc291ZmZsw6kgYnJvd25pZSBpY2UgY3JlYW0uIEp1anViZXMgY2FrZSBjdXBjYWtlIG1hY2Fyb29uIGRhbmlzaCBqZWxseS1vIHNvdWZmbMOpLiBDYWtlIGFwcGxlIHBpZSBnaW5nZXJicmVhZCBjaG9jb2xhdGUgc3VnYXIgcGx1bS4gU3dlZXQgY2hvY29sYXRlIGNha2UgY2hvY29sYXRlIGNha2UganVqdWJlcyB0aXJhbWlzdSBvYXQgY2FrZS4gU3dlZXQgc291ZmZsw6kgY2hvY29sYXRlLiBMaXF1b3JpY2UgY290dG9uIGNhbmR5IGNob2NvbGF0ZSBtYXJzaG1hbGxvdy4gSmVsbHkgY29va2llIGNha2UgamVsbHkgYm==
The following operation uses mongoimport
with the—fields
and—columnsHaveTypes
optionto specify both the field names and the BSON types of the imported CSVdata.
- mongoimport --db=users --collection=contacts --type=csv \
- --columnsHaveTypes \
- --fields="name.string(),birthdate.date(2006-01-02),contacted.boolean(),followerCount.int32(),thumbnail.binary(base64)" \
- --file=/example/file.csv
Ignore Blank Fields
Use the —ignoreBlanks
optionto ignore blank fields. For CSV and TSV imports, thisoption provides the desired functionality in most cases because it avoidsinserting fields with null values into your collection.
The following example imports the data from data.csv
, skippingany blank fields:
- mongoimport --db=users --collection=contacts --type=csv --file=/example/data.csv --ignoreBlanks