mongoimport: JSON ve CSV Dosyalarını Yükleme
Öğrenenler, çeşitli kip seçeneklerini kullanarak JSON ve CSV veri dosyalarını mongoimport ile bir koleksiyona aktaracaklardır.
mongoimport: JSON ve CSV Dosyalarını Yükleme, CoddyKit'te ücretsiz bir MongoDB Academy dersidir. Bu, 4 dersinin 1. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, MongoDB Academy öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. MongoDB Academy kursu toplamda 4 dersten oluşur.
Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.
What Is mongoimport?
mongoimport is a command-line tool bundled with the MongoDB Database Tools package. It loads data from JSON, JSONL (JSON Lines / newline-delimited JSON), and CSV files directly into a MongoDB collection. It is the standard way to seed a collection with initial data, migrate from another database, or bulk-load a data export from a third-party system.
Basic JSON Import
The simplest mongoimport command specifies the connection string, database, collection, and input file. By default it expects a JSON array of objects ([{...},{...}]). The --jsonArray flag is required when importing a file that contains a JSON array; omit it for JSONL (one document per line) format.
# Import a JSON array file into the 'products' collection
mongoimport \
--uri 'mongodb://localhost:27017/myapp' \
--collection products \
--file products.json \
--jsonArray
# Output:
# 2024-01-01T12:00:00.000+0000 connected to: mongodb://localhost:27017
# 2024-01-01T12:00:00.100+0000 100 document(s) imported successfullyJSONL Format: One Document Per Line
JSONL (also called ndjson) stores one JSON document per line with no outer array wrapper. This format is preferred for large files because it can be streamed and processed line-by-line without loading the entire file into memory. mongoimport handles JSONL by default when you omit --jsonArray.
# products.ndjson — one document per line:
# {"name":"Widget","price":9.99}
# {"name":"Gadget","price":19.99}
# {"name":"Donut","price":1.99}
# Import JSONL file (no --jsonArray flag)
mongoimport \
--uri 'mongodb://localhost:27017/myapp' \
--collection products \
--file products.ndjsonImporting CSV Files
For CSV imports, specify --type csv and provide column headers. If the CSV file has a header row, use --headerline to read column names from the first row. If the file has no header row, list the column names with --fields. All CSV values are imported as strings by default—use --columnsHaveTypes to declare types.
# CSV with header row:
# name,price,category
# Widget,9.99,tools
# Gadget,19.99,electronics
mongoimport \
--uri 'mongodb://localhost:27017/myapp' \
--collection products \
--type csv \
--headerline \
--file products.csvSpecifying Field Names for Headerless CSV
When the CSV file lacks a header row, list the field names with the --fields flag. The order of names in --fields must match the column order in the CSV. This approach is common when importing exports from legacy systems that don't include headers.
# CSV without header:
# Widget,9.99,tools
# Gadget,19.99,electronics
mongoimport \
--uri 'mongodb://localhost:27017/myapp' \
--collection products \
--type csv \
--fields 'name,price,category' \
--file products_no_header.csvImport Modes: insert, upsert, merge
mongoimport supports three write modes controlled by --mode:
insert(default): insert all documents; fails on duplicate_idupsert: insert if not exists, replace if exists (matching on--upsertFields)merge: insert if not exists, merge fields if exists without replacing the whole document
upsert for idempotent re-imports.# Upsert mode — safe to run multiple times
mongoimport \
--uri 'mongodb://localhost:27017/myapp' \
--collection products \
--file products.json \
--jsonArray \
--mode upsert \
--upsertFields 'sku' # match on the 'sku' fieldThe --drop Flag: Replace Collection Contents
The --drop flag drops the target collection before importing. This gives you a clean slate on each import, useful for seeding a development environment where you want to reset data to a known state. Do not use --drop in production if the collection holds data that should not be wiped.
# Drop the products collection and reimport from scratch
mongoimport \
--uri 'mongodb://localhost:27017/myapp' \
--collection products \
--file products.json \
--jsonArray \
--drop # drops collection before importingImporting Into MongoDB Atlas
To import into a MongoDB Atlas cluster, use the full Atlas connection string (SRV format) in the --uri flag. Atlas requires TLS—the SRV URI automatically enables it. You will need your Atlas username and password in the URI or passed via environment variables to avoid storing credentials in shell history.
# Import into Atlas cluster
MONGO_URI='mongodb+srv://username:password@cluster0.abc.mongodb.net/myapp'
mongoimport \
--uri "$MONGO_URI" \
--collection products \
--file products.json \
--jsonArrayHandling Import Errors
mongoimport continues on non-fatal errors (like duplicate key violations on individual documents) by default and logs a count of failed documents at the end. Use --stopOnError to halt the import on the first error—useful when you need all-or-nothing import semantics. Check the exit code and error count in scripts to detect partial imports.
# Stop the entire import if any document fails
mongoimport \
--uri 'mongodb://localhost:27017/myapp' \
--collection products \
--file products.json \
--jsonArray \
--stopOnError
# Check exit code in a script
if [ $? -ne 0 ]; then
echo 'Import failed!'
exit 1
fiChecking mongoimport Version and Installation
mongoimport is part of the MongoDB Database Tools package, which is installed separately from mongod. Verify it is installed with mongoimport --version. On Atlas clusters you can also use the Atlas UI's Data Import feature for small files, or Atlas Data Federation for larger data lake imports. Always match the tools version to your server version to avoid compatibility issues.
# Verify installation
mongoimport --version
# mongodb-database-tools version: 100.9.0
# git version: ...
# Go version: ...
# Install on macOS with Homebrew
# brew install mongodb/brew/mongodb-database-toolsImport Performance Tips
For large imports (millions of documents), these settings significantly improve throughput: (1) Use --numInsertionWorkers to parallelise insertions (default 1, try 4 for bulk loads); (2) Drop indexes before import and rebuild them after—index maintenance during bulk insert is expensive; (3) Use JSONL format instead of a large JSON array to enable streaming; (4) Import from a host close to the MongoDB server to minimise network latency.
# High-throughput bulk import with 4 parallel workers
mongoimport \
--uri 'mongodb://localhost:27017/myapp' \
--collection events \
--file events.ndjson \
--numInsertionWorkers 4Quick Check
Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.
Lesson Recap
In this lesson you learned: mongoimport loads JSON, JSONL, and CSV files into a collection via the command line, --mode upsert makes imports idempotent using a specified match field, and --numInsertionWorkers and dropping indexes before bulk imports improve performance. Next up we explore mongoexport for dumping collection data to files.
Sıkça Sorulan Sorular
“mongoimport: JSON ve CSV Dosyalarını Yükleme” dersi ücretsiz mi?
Evet — “mongoimport: JSON ve CSV Dosyalarını Yükleme” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve MongoDB Academy kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. MongoDB Academy kursu toplamda 4 dersten oluşur.
“mongoimport: JSON ve CSV Dosyalarını Yükleme” dersinde ne öğreneceğim?
Öğrenenler, çeşitli kip seçeneklerini kullanarak JSON ve CSV veri dosyalarını mongoimport ile bir koleksiyona aktaracaklardır. MongoDB Academy ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.
MongoDB Academy öğrenmeye başlamak için deneyim gerekli mi?
Önceden deneyim gerekmez. CoddyKit'te MongoDB Academy, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 1. dersidir.
“mongoimport: JSON ve CSV Dosyalarını Yükleme” dersi ne kadar sürer?
Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.
Bu MongoDB Academy dersinde kod yazıp çalıştırabilir miyim?
Evet. Her MongoDB Academy dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.
Bu kursun tüm dersleri
- mongoimport: JSON ve CSV Dosyalarını Yükleme
- mongoexport: Koleksiyonları Dosyalara Aktarma
- Tam Yedeklemeler İçin mongodump ve mongorestore
- Node.js Betikleriyle Veri Tohumlama