MongoDB proporciona la mongoimportHerramienta para importar archivos JSON y CSV a tu conjunto de datos principal. Esta guía explica cómo usar eficazmente mongoimport para transferir tus datos a tu base de datos MongoDB.
Antes de comenzar
Siga la Guía de instalación de herramientas de base de
mongoimportdatos para instalar.Crea los archivos de ejemplo.
2Crear
.jsonarchivos de ejemplo@' { "tripduration": 602, "starttime": "2019-12-01 00:00:05.5640", "stoptime": "2019-12-01 00:10:07.8180", "start station id": 3382, "start station name": "Carroll St & Smith St", "start station latitude": 40.680611, "start station longitude": -73.99475825, "end station id": 3304, "end station name": "6 Ave & 9 St", "end station latitude": 40.668127, "end station longitude": -73.98377641, "bikeid": 41932, "usertype": "Subscriber", "birth year": 1970, "gender": "male" } '@ | Set-Content -Path ride_01.json @' { "tripduration": 1206, "starttime": "2019-12-01 00:00:10.9630", "stoptime": "2019-12-01 00:20:17.8820", "start station id": 362, "start station name": "Broadway & W 37 St", "start station latitude": 40.75172632, "start station longitude": -73.98753523, "end station id": 500, "end station name": "Broadway & W 51 St", "end station latitude": 40.76228826, "end station longitude": -73.98336183, "bikeid": 18869, "usertype": "Customer", "birth year": 1999, "gender": "male" } '@ | Set-Content -Path ride_02.json @' { "tripduration": 723, "starttime": "2019-12-01 00:00:11.8180", "stoptime": "2019-12-01 00:12:14.8310", "start station id": 146, "start station name": "Hudson St & Reade St", "start station latitude": 40.71625008, "start station longitude": -74.0091059, "end station id": 238, "end station name": "Bank St & Washington St", "end station latitude": 40.7361967, "end station longitude": -74.00859207, "bikeid": 15334, "usertype": "Subscriber", "birth year": 1997, "gender": "male" } '@ | Set-Content -Path ride_03.json @' [ { "tripduration": 602, "starttime": "2019-12-01 00:00:05.5640", "stoptime": "2019-12-01 00:10:07.8180", "start station id": 3382, "start station name": "Carroll St & Smith St", "start station latitude": 40.680611, "start station longitude": -73.99475825, "end station id": 3304, "end station name": "6 Ave & 9 St", "end station latitude": 40.668127, "end station longitude": -73.98377641, "bikeid": 41932, "usertype": "Subscriber", "birth year": 1970, "gender": "male" }, { "tripduration": 1206, "starttime": "2019-12-01 00:00:10.9630", "stoptime": "2019-12-01 00:20:17.8820", "start station id": 362, "start station name": "Broadway & W 37 St", "start station latitude": 40.75172632, "start station longitude": -73.98753523, "end station id": 500, "end station name": "Broadway & W 51 St", "end station latitude": 40.76228826, "end station longitude": -73.98336183, "bikeid": 18869, "usertype": "Customer", "birth year": 1999, "gender": "male" }, { "tripduration": 723, "starttime": "2019-12-01 00:00:11.8180", "stoptime": "2019-12-01 00:12:14.8310", "start station id": 146, "start station name": "Hudson St & Reade St", "start station latitude": 40.71625008, "start station longitude": -74.0091059, "end station id": 238, "end station name": "Bank St & Washington St", "end station latitude": 40.7361967, "end station longitude": -74.00859207, "bikeid": 15334, "usertype": "Subscriber", "birth year": 1997, "gender": "male" } ] '@ | Set-Content -Path rides.json @' 602,"2019-12-01 00:00:05.5640","2019-12-01 00:10:07.8180",3382,"Carroll St & Smith St",40.680611,-73.99475825,3304,"6 Ave & 9 St",40.668127,-73.98377641,41932,"Subscriber",1970,1 1206,"2019-12-01 00:00:10.9630","2019-12-01 00:20:17.8820",362,"Broadway & W 37 St",40.75172632,-73.98753523,500,"Broadway & W 51 St",40.76228826,-73.98336183,18869,"Customer",1999,1 723,"2019-12-01 00:00:11.8180","2019-12-01 00:12:14.8310",146,"Hudson St & Reade St",40.71625008,-74.0091059,238,"Bank St & Washington St",40.7361967,-74.00859207,15334,"Subscriber",1997,1 '@ | Set-Content -Path rides_no_header.json 2Crear
.jsonarchivos de ejemploecho '{ "tripduration": 602, "starttime": "2019-12-01 00:00:05.5640", "stoptime": "2019-12-01 00:10:07.8180", "start station id": 3382, "start station name": "Carroll St & Smith St", "start station latitude": 40.680611, "start station longitude": -73.99475825, "end station id": 3304, "end station name": "6 Ave & 9 St", "end station latitude": 40.668127, "end station longitude": -73.98377641, "bikeid": 41932, "usertype": "Subscriber", "birth year": 1970, "gender": "male" }' > ride_01.json echo '{ "tripduration": 1206, "starttime": "2019-12-01 00:00:10.9630", "stoptime": "2019-12-01 00:20:17.8820", "start station id": 362, "start station name": "Broadway & W 37 St", "start station latitude": 40.75172632, "start station longitude": -73.98753523, "end station id": 500, "end station name": "Broadway & W 51 St", "end station latitude": 40.76228826, "end station longitude": -73.98336183, "bikeid": 18869, "usertype": "Customer", "birth year": 1999, "gender": "male" }' > ride_02.json echo '{ "tripduration": 723, "starttime": "2019-12-01 00:00:11.8180", "stoptime": "2019-12-01 00:12:14.8310", "start station id": 146, "start station name": "Hudson St & Reade St", "start station latitude": 40.71625008, "start station longitude": -74.0091059, "end station id": 238, "end station name": "Bank St & Washington St", "end station latitude": 40.7361967, "end station longitude": -74.00859207, "bikeid": 15334, "usertype": "Subscriber", "birth year": 1997, "gender": "male" }' > ride_03.json echo '[ { "tripduration": 602, "starttime": "2019-12-01 00:00:05.5640", "stoptime": "2019-12-01 00:10:07.8180", "start station id": 3382, "start station name": "Carroll St & Smith St", "start station latitude": 40.680611, "start station longitude": -73.99475825, "end station id": 3304, "end station name": "6 Ave & 9 St", "end station latitude": 40.668127, "end station longitude": -73.98377641, "bikeid": 41932, "usertype": "Subscriber", "birth year": 1970, "gender": "male" }, { "tripduration": 1206, "starttime": "2019-12-01 00:00:10.9630", "stoptime": "2019-12-01 00:20:17.8820", "start station id": 362, "start station name": "Broadway & W 37 St", "start station latitude": 40.75172632, "start station longitude": -73.98753523, "end station id": 500, "end station name": "Broadway & W 51 St", "end station latitude": 40.76228826, "end station longitude": -73.98336183, "bikeid": 18869, "usertype": "Customer", "birth year": 1999, "gender": "male" }, { "tripduration": 723, "starttime": "2019-12-01 00:00:11.8180", "stoptime": "2019-12-01 00:12:14.8310", "start station id": 146, "start station name": "Hudson St & Reade St", "start station latitude": 40.71625008, "start station longitude": -74.0091059, "end station id": 238, "end station name": "Bank St & Washington St", "end station latitude": 40.7361967, "end station longitude": -74.00859207, "bikeid": 15334, "usertype": "Subscriber", "birth year": 1997, "gender": "male" } ]' > rides.json echo '602,"2019-12-01 00:00:05.5640","2019-12-01 00:10:07.8180",3382,"Carroll St & Smith St",40.680611,-73.99475825,3304,"6 Ave & 9 St",40.668127,-73.98377641,41932,"Subscriber",1970,1 1206,"2019-12-01 00:00:10.9630","2019-12-01 00:20:17.8820",362,"Broadway & W 37 St",40.75172632,-73.98753523,500,"Broadway & W 51 St",40.76228826,-73.98336183,18869,"Customer",1999,1 723,"2019-12-01 00:00:11.8180","2019-12-01 00:12:14.8310",146,"Hudson St & Reade St",40.71625008,-74.0091059,238,"Bank St & Washington St",40.7361967,-74.00859207,15334,"Subscriber",1997,1 ' > rides_no_header.json 2Crear
.jsonarchivos de ejemplocat << 'EOF' > ride_01.json { "tripduration": 602, "starttime": "2019-12-01 00:00:05.5640", "stoptime": "2019-12-01 00:10:07.8180", "start station id": 3382, "start station name": "Carroll St & Smith St", "start station latitude": 40.680611, "start station longitude": -73.99475825, "end station id": 3304, "end station name": "6 Ave & 9 St", "end station latitude": 40.668127, "end station longitude": -73.98377641, "bikeid": 41932, "usertype": "Subscriber", "birth year": 1970, "gender": "male" } EOF cat << 'EOF' > ride_02.json { "tripduration": 1206, "starttime": "2019-12-01 00:00:10.9630", "stoptime": "2019-12-01 00:20:17.8820", "start station id": 362, "start station name": "Broadway & W 37 St", "start station latitude": 40.75172632, "start station longitude": -73.98753523, "end station id": 500, "end station name": "Broadway & W 51 St", "end station latitude": 40.76228826, "end station longitude": -73.98336183, "bikeid": 18869, "usertype": "Customer", "birth year": 1999, "gender": "male" } EOF cat << 'EOF' > ride_03.json { "tripduration": 723, "starttime": "2019-12-01 00:00:11.8180", "stoptime": "2019-12-01 00:12:14.8310", "start station id": 146, "start station name": "Hudson St & Reade St", "start station latitude": 40.71625008, "start station longitude": -74.0091059, "end station id": 238, "end station name": "Bank St & Washington St", "end station latitude": 40.7361967, "end station longitude": -74.00859207, "bikeid": 15334, "usertype": "Subscriber", "birth year": 1997, "gender": "male" } EOF cat << 'EOF' > rides.json [ { "tripduration": 602, "starttime": "2019-12-01 00:00:05.5640", "stoptime": "2019-12-01 00:10:07.8180", "start station id": 3382, "start station name": "Carroll St & Smith St", "start station latitude": 40.680611, "start station longitude": -73.99475825, "end station id": 3304, "end station name": "6 Ave & 9 St", "end station latitude": 40.668127, "end station longitude": -73.98377641, "bikeid": 41932, "usertype": "Subscriber", "birth year": 1970, "gender": "male" }, { "tripduration": 1206, "starttime": "2019-12-01 00:00:10.9630", "stoptime": "2019-12-01 00:20:17.8820", "start station id": 362, "start station name": "Broadway & W 37 St", "start station latitude": 40.75172632, "start station longitude": -73.98753523, "end station id": 500, "end station name": "Broadway & W 51 St", "end station latitude": 40.76228826, "end station longitude": -73.98336183, "bikeid": 18869, "usertype": "Customer", "birth year": 1999, "gender": "male" }, { "tripduration": 723, "starttime": "2019-12-01 00:00:11.8180", "stoptime": "2019-12-01 00:12:14.8310", "start station id": 146, "start station name": "Hudson St & Reade St", "start station latitude": 40.71625008, "start station longitude": -74.0091059, "end station id": 238, "end station name": "Bank St & Washington St", "end station latitude": 40.7361967, "end station longitude": -74.00859207, "bikeid": 15334, "usertype": "Subscriber", "birth year": 1997, "gender": "male" } ] EOF cat << 'EOF' > rides_no_header.json 602,"2019-12-01 00:00:05.5640","2019-12-01 00:10:07.8180",3382,"Carroll St & Smith St",40.680611,-73.99475825,3304,"6 Ave & 9 St",40.668127,-73.98377641,41932,"Subscriber",1970,1 1206,"2019-12-01 00:00:10.9630","2019-12-01 00:20:17.8820",362,"Broadway & W 37 St",40.75172632,-73.98753523,500,"Broadway & W 51 St",40.76228826,-73.98336183,18869,"Customer",1999,1 723,"2019-12-01 00:00:11.8180","2019-12-01 00:12:14.8310",146,"Hudson St & Reade St",40.71625008,-74.0091059,238,"Bank St & Washington St",40.7361967,-74.00859207,15334,"Subscriber",1997,1 EOF Encuentra tu cadena de conexión de MongoDB.
Importante
Su cadena de conexión de MongoDB Atlas se asemeja al siguiente ejemplo:
mongodb+srv://myDatabaseUser:D1fficultP%40ssw0rd@cluster0.example.mongodb.net/?retryWrites=true&w=majority
Introducción a mongoimport
mongoimport es una herramienta de línea de comandos para importar datos de archivos JSON, CSV y TSV a colecciones de MongoDB. se puede combinar con otrasmongoimport herramientas de línea de comandos como JQ para la manipulación deJSON, CSVKit para la manipulación de CSV o curl para descargar dinámicamente archivos de datos de servidores en Internet.
Elige un formato de datos de origen
JSON es un formato de datos jerárquico, como los documentos MongoDB, y también es explícito sobre los tipos de datos que codifica.
Los datos CSV (y TSV) son tabulares y cada fila se importará a MongoDB como un documento independiente. Esto significa que estos formatos no admiten datos jerárquicos como un documento MongoDB. Al importar datos CSV a MongoDB, intenta tomar decisiones acertadas al identificar el tipo de campo específico. Este comportamiento se puede anular con indicadores o la especificación demongoimport tipo.
Conecte mongoimport a su base de datos
Utilice la cadena de conexión de MongoDB Atlas para conectar a mongoimport la test base de datos y a la test-collection colección.
mongoimport --uri 'mongodb+srv://myDatabaseUser:D1fficultP%40ssw0rd@cluster0.example.mongodb.net/?retryWrites=true&w=majority' \ --db=test \ --collection=test-collection
La conexión exitosa a su colección de bases de datos se parece a lo siguiente:
2025-07-14T10:22:58.317-0400 connected to: mongodb+srv://cluster0.zoikgns.mongodb.net/ 2025-07-14T10:23:01.318-0400 test.test-collection 0B 2025-07-14T10:23:04.318-0400 test.test-collection 0B ...
Después de conectarse a su colección de bases de datos satisfactoriamente, siga los ejemplos para aprender a utilizar mongoimport para importar datos en MongoDB.
Pasos
Los siguientes ejemplos le muestran cómo:
Importar CSV o TSV en una colección con tipos de campo especificados
Importar CSV o TSV a una colección con campos y tipos de datos especificados
Importar documentos con --file
Utilice la opción para especificar la ubicación y el nombre del archivo que contiene los datos que se importarán a una colección --file MongoDB.
El siguiente ejemplo importa el archivo ride_01.json a la nueva colección, test-collection, en la base de datos test proporcionando la ruta del archivo --file=ride_01.json.
mongoimport --uri 'mongodb+srv://myDatabaseUser:D1fficultP%40ssw0rd@cluster0.example.mongodb.net/?retryWrites=true&w=majority' \ --db=test \ --collection=test-collection \ --file=ride_01.json
Una importación exitosa se parece a lo siguiente:
2025-07-14T11:47:01.303-0400 connected to: mongodb+srv://[**REDACTED**]@cluster0.zoikgns.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0 2025-07-14T11:47:01.391-0400 1 document(s) imported successfully. 0 document(s) failed to import.
Para ver la importación de datos exitosa, puede utilizar la interfaz de usuario de Atlas.

Nota
Para cada documento importado, MongoDB genera un valor _id único requerido.
Si no se especifica un archivo, mongoimport lee los datos de la entrada estándar (p. stdin ej.,). El siguiente ejemplo muestra cómo importar varios documentos canalizándolos mongoimport a, que a su vez lee los datos stdin de.
echo "{\"bikeid\":\"1234\"}\n{\"bikeid\":\"5678\"}" | mongoimport --uri 'mongodb+srv://myDatabaseUser:D1fficultP%40ssw0rd@cluster0.example.mongodb.net/?retryWrites=true&w=majority' \ --db=test \ --collection=test-collection-stdin
Una importación exitosa se parece a lo siguiente:
2025-07-14T11:08:08.884-0600 connected to: mongodb+srv://[**REDACTED**]@cluster0.zoikgns.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0 2025-07-14T11:08:09.095-0600 2 document(s) imported successfully. 0 document(s) failed to import.
Importar documentos con canalización
Puedes canalizar varios documentos JSON desde otra herramienta,cat como, para importar varios archivos con. Desde el directorio que contiene los archivos JSON para importar, puedes ejecutar el siguiente comando para importar los mongoimport documentos.
cat *_*.json | mongoimport --uri 'mongodb+srv://myDatabaseUser:D1fficultP%40ssw0rd@cluster0.example.mongodb.net/?retryWrites=true&w=majority' \ --db=test \ --collection=test-collection-many
Una importación exitosa se parece a lo siguiente:
2025-07-21T16:48:23.519-0400 connected to: mongodb+srv://[**REDACTED**]@cluster0.zoikgns.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0 2025-07-21T16:48:23.627-0400 3 document(s) imported successfully. 0 document(s) failed to import.
Import a JSON Array
Para importar un arreglo JSON de documentos, puedes usar la opción --jsonArray para especificar el formato de los datos. Debe especificar la fuente de datos, que puede ser un archivo o una entrada estándar, por separado. El siguiente ejemplo importa el archivo rides.json que contiene un único arreglo JSON.
mongoimport --uri 'mongodb+srv://myDatabaseUser:D1fficultP%40ssw0rd@cluster0.example.mongodb.net/?retryWrites=true&w=majority' \ --db=test \ --collection=test-collection-array \ --file=rides.json \ --jsonArray
Una importación exitosa se parece a lo siguiente:
2025-07-14T11:48:10.829-0400 connected to: mongodb+srv://[**REDACTED**]@cluster0.zoikgns.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0 2025-07-14T11:48:10.899-0400 3 document(s) imported successfully. 0 document(s) failed to import.
Si no agrega la --jsonArray opción, fallará con elmongoimport error cannot decode array into a Document porque los documentos MongoDB son comparables a objetos JSON, no a matrices.
Nota
Puede almacenar una matriz como valor en un documento, pero un documento no puede ser una matriz.
Importar tipos específicos de MongoDB con JSON
Dado que MongoDB almacena datos como BSON, debe usar JSON extendido para reconocer los campos importados como JSON como tipos BSON específicos. Esto significa que puede proporcionar un campo que MongoDB reconoce originalmente como string en la siguiente estructura anidada para que MongoDB lo reconozca como date tipo.
"starttime": { "$date": "2019-12-01T00:00:05.5640Z" }
Para transformar sus datos existentes, consulte la sección sobre JQ.
Importar CSV o TSV en una colección con tipos de campo especificados
Si tiene archivos CSV o TSV para importar, utilice o,--type=csv respectivamente, para indicar a el formato --type=tsv mongoimport que debe esperar.
Si su archivo CSV o TSV tiene una fila de encabezado, use la opción --headerline mongoimport para indicar a que la primera línea no debe importarse como documento.
Dado que los datos CSV y TSV no incluyen información sobre el tipo, puedes resolver esto especificando los tipos de campos cuando llames a mongoimport. La primera forma de proporcionar mongoimport con información de tipo es si se enumeran los nombres de los campos en la línea de comandos con la opción --fields.
mongoimport --uri 'mongodb+srv://myDatabaseUser:D1fficultP%40ssw0rd@cluster0.example.mongodb.net/?retryWrites=true&w=majority' \ --db=test \ --collection=test-field-file \ --file=rides_no_header.csv \ --type=csv \ --fields="tripduration","starttime","stoptime","start station id","start station name","start station latitude","start station longitude","end station id","end station name","end station latitude","end station longitude","bikeid","usertype","birth year","gender"
Otra forma de proporcionar información de tipo a es si coloca los nombres de los campos en un mongoimport archivo,field_file.txt como, y lo apunta con la --fieldFile opción.
@" tripduration starttime stoptime start station id start station name start station latitude start station longitude end station id end station name end station latitude end station longitude bikeid usertype birth year gender "@ | Set-Content -Path field_file.txt
echo 'tripduration starttime stoptime start station id start station name start station latitude start station longitude end station id end station name end station latitude end station longitude bikeid usertype birth year gender' > field_file.txt
cat << 'EOF' > field_file.txt tripduration starttime stoptime start station id start station name start station latitude start station longitude end station id end station name end station latitude end station longitude bikeid usertype birth year gender EOF
mongoimport --uri 'mongodb+srv://myDatabaseUser:D1fficultP%40ssw0rd@cluster0.example.mongodb.net/?retryWrites=true&w=majority' \ --db=test \ --collection=test-field-file \ --file=rides_no_header.csv \ --type=csv \ --fieldFile=field_file.txt
La importación exitosa de las opciones --fields y se parece a lo --fieldFile siguiente:
2025-07-14T11:48:10.829-0400 connected to: mongodb+srv://[**REDACTED**]@cluster0.zoikgns.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0 2025-07-14T11:48:10.899-0400 3 document(s) imported successfully. 0 document(s) failed to import.
Para ver la importación de datos exitosa, puede utilizar la interfaz de usuario de Atlas.

Importar CSV o TSV a una colección con campos y tipos de datos especificados
Arriba, puede ver que toma decisiones automáticamente sobre los tipos de datos. Para especificar mongoimport el tipo de algunos o todos los campos, puede usar la opción o agregar tipos --columnsHaveTypes --fieldFile al archivo que usa con la opción.
@" tripduration.auto() starttime.date(2006-01-02 15:04:05) stoptime.date(2006-01-02 15:04:05) start station id.auto() start station name.auto() start station latitude.auto() start station longitude.auto() end station id.auto() end station name.auto() end station latitude.auto() end station longitude.auto() bikeid.auto() usertype.auto() birth year.auto() gender.auto() "@ | Set-Content -Path field_file_with_types.txt
echo 'tripduration.auto() starttime.date(2006-01-02 15:04:05) stoptime.date(2006-01-02 15:04:05) start station id.auto() start station name.auto() start station latitude.auto() start station longitude.auto() end station id.auto() end station name.auto() end station latitude.auto() end station longitude.auto() bikeid.auto() usertype.auto() birth year.auto() gender.auto()' > field_file_with_types.txt
cat << 'EOF' > field_file_with_types.txt tripduration.auto() starttime.date(2006-01-02 15:04:05) stoptime.date(2006-01-02 15:04:05) start station id.auto() start station name.auto() start station latitude.auto() start station longitude.auto() end station id.auto() end station name.auto() end station latitude.auto() end station longitude.auto() bikeid.auto() usertype.auto() birth year.auto() gender.auto() EOF
mongoimport --uri 'mongodb+srv://myDatabaseUser:D1fficultP%40ssw0rd@cluster0.example.mongodb.net/?retryWrites=true&w=majority' \ --db=test \ --collection=test-field-file \ --file=test-datasets/rides_no_header.csv \ --type=csv \ --fieldFile=field_file_with_types.txt
Una importación exitosa se parece a lo siguiente:
2025-07-14T11:48:10.829-0400 connected to: mongodb+srv://[**REDACTED**]@cluster0.zoikgns.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0 2025-07-14T11:48:10.899-0400 3 document(s) imported successfully. 0 document(s) failed to import.
Para ver la importación de datos exitosa, puede utilizar la interfaz de usuario de Atlas.

Ahora, puedes ver que usa los tipos de datos que proporcionas para almacenar el archivo mongoimport importado.
Herramientas útiles de línea de comandos
Puedes usar otros programas de línea de comando junto con mongoimport para agilizar aún más tu importación de datos.
JQ
JQ es un procesador de datos JSON. Incorpora un potente lenguaje de filtrado y scripting para filtrar, manipular y generar datos JSON. Puede usar una tubería multietapa para canalizar datos a mediante JQ. Para obtener más información sobre cómo usar JQ, consulte el mongoimport Manualde JQ.
CSVKit
CSVKit es una colección de herramientas para filtrar y manipular datos CSV. Herramientas de CSVKit csvgrep como, que filtra filas según expresiones, y,csvcut que elimina columnas completas de la entrada CSV, son útiles para segmentar los datos antes de proporcionarlos a. Para obtener más información sobre cómo usar CSVKit, consulte la mongoimport documentaciónde CSVKit.
Obtén más información
Consulta nuestra documentación
mongoimportpara obtener más detalles sobre las posibles opciones.