❯ man spanna/guides
Import JSON into MongoDB
Learn how to import JSON into MongoDB safely, preserve the right data types, avoid common `mongoimport` mistakes, and verify the result properly.
› /docs/import-json-into-mongodb
Importing JSON into MongoDB looks easy right up until you import the wrong file, flatten a type you meant to preserve, or discover after the fact that every _id value was regenerated.
The good news is that JSON imports are predictable when you treat them like data changes, not like file uploads.
This guide walks through the safe path: validate the file, understand the type implications, import deliberately, and verify the result before you trust it.
The first question: what kind of JSON do you actually have?
MongoDB stores data as BSON, not plain JSON.
That distinction matters because normal JSON does not natively preserve every BSON type. Dates, ObjectIds, decimal values, and binary data can all lose fidelity if the file was produced carelessly.
MongoDB’s current tools documentation is explicit here:
mongoimportexpects Extended JSON by defaultmongoexportandmongoimportwork best when they use matching versions- if your file is a JSON array, you need
--jsonArray
So before importing anything, answer these questions:
- is the file newline-delimited JSON documents, or one big JSON array?
- was it exported from MongoDB tools, or generated by an app?
- do you need to preserve BSON types like ObjectId or Date?
- do the documents already contain
_idvalues?
Those four answers tell you whether the import will be straightforward or risky.
The safest mental model
Think of a JSON import as a controlled write operation into a live collection.
That means you should care about:
- the destination collection
- the shape of the incoming documents
- whether
_idvalues collide - whether validation rules will reject the write
- whether the import should append, replace, or seed brand-new data
If you skip those decisions, mongoimport will still happily do something. It just might not do the thing you wanted.
Before you import
1. Confirm the target environment
This is the most boring step, and the most important one.
Make sure you know:
- the cluster
- the database
- the collection
- whether the target is empty, partial, or already in use
A correct import into the wrong environment is still a bad incident.
2. Inspect a sample of the file
Do not trust the filename. Open the file and read actual records.
You are looking for:
_idvalues- date formatting
- nested objects and arrays
- any obviously environment-specific data
- whether the payload is one document per line or a JSON array
If the file starts like this:
[
{ "_id": 1, "name": "A" },
{ "_id": 2, "name": "B" }
]
that is a JSON array, and mongoimport needs --jsonArray.
MongoDB’s official mongoimport guide calls this out directly: without --jsonArray, importing an array file fails because MongoDB expects documents, not one top-level array value.
3. Decide what should happen with _id
This is where many imports go sideways.
If the JSON already includes _id:
- duplicate
_idvalues can fail the import - preserved
_idvalues can be exactly what you want for migration or restore-style workflows
If the JSON does not include _id:
- MongoDB generates new
_idvalues during insert
That is fine for fixture loading or first-time seeding. It is not fine if you are trying to preserve identity across environments.
4. Check collection validation rules
MongoDB schema validation can reject inserts that do not match the expected shape or types.
That is usually a good thing. It prevents bad imports from silently poisoning the collection.
But it also means you should know whether the destination collection has validation enabled before you import a large file and assume it will all land cleanly.
Use the right import shape
Newline-delimited JSON
This is usually the easiest format for imports:
{ "_id": 1, "name": "A" }
{ "_id": 2, "name": "B" }
JSON array
This is also valid, but you must import it as an array:
mongoimport --uri "<connection-string>" \
--db app \
--collection users \
--file users.json \
--jsonArray
If you forget --jsonArray, the import can fail with the exact class of error MongoDB documents in its examples.
Preserve types when it matters
If the file came from MongoDB and you care about type fidelity, Extended JSON matters.
MongoDB’s tools docs note that:
mongoexportuses Extended JSON v2- relaxed mode is the default
- canonical mode is better when you need strict BSON type preservation
That means this export:
mongoexport --uri "<connection-string>" \
--db app \
--collection orders \
--jsonFormat=canonical \
--out orders.json
is a safer handoff for round-tripping BSON-heavy data than casual app-generated JSON.
If your JSON was not produced with MongoDB tooling, be extra careful with:
- dates represented as plain strings
- ObjectIds represented as plain strings
- decimals that should not become floating-point numbers
Common mongoimport workflows
Import a JSON array into a collection
mongoimport --uri "<connection-string>" \
--db app \
--collection products \
--file products.json \
--jsonArray
Import newline-delimited JSON
mongoimport --uri "<connection-string>" \
--db app \
--collection products \
--file products.ndjson
Import into Atlas
MongoDB’s Atlas docs support mongoimport as a standard way to load JSON or CSV into Atlas clusters, as long as the target user has the required permissions and network access is configured correctly.
What can go wrong
1. Wrong collection
You meant staging.users. You imported into production.users.
This is the classic human error. Defend against it with explicit environment checks before you run the command.
2. Duplicate _id collisions
If incoming documents reuse _id values that already exist, the import may fail or partially succeed depending on how you run it and what options you use.
3. Type drift
A date string that should have been a BSON date remains a string. An ObjectId becomes plain text. The import succeeds, but the application now behaves differently.
This is one of the most dangerous failure modes because it looks successful at first glance.
4. Wrong file shape
A JSON array imported without --jsonArray is one of the most common avoidable errors.
5. Validation rejection
The collection has schema validation, and some documents fail. Good protection, but only if you notice and review the failure.
How to verify the import properly
Do not stop at “command finished.”
Use a verification sequence:
- check the final document count
- inspect a sample of imported documents
- confirm important fields have the right types
- verify
_idvalues were preserved if that mattered - compare against the source file or source environment when relevant
MongoDB recommends modern count APIs like countDocuments() rather than older count() helpers for logical document counts. That is the better post-import validation check.
Example:
db.products.countDocuments()
Then inspect a few real records:
db.products.find().limit(5)
If the import was meant to preserve BSON-heavy values, inspect those fields specifically rather than assuming they survived correctly.
When JSON import is the wrong tool
Sometimes you should not be using JSON import at all.
If the goal is:
- backup and restore
- same-version MongoDB migration
- preserving the database as faithfully as possible
then mongodump and mongorestore are often a better fit than mongoexport and mongoimport.
MongoDB’s tooling docs make that distinction clear: JSON tools are excellent for data movement and selective exports, but BSON dump/restore workflows are the better choice for full-fidelity backup-style tasks.
How Spanna helps
Spanna is useful here because a safe import is half command execution and half validation:
- confirm the target collection
- preview the collection before import
- inspect the result after import
- compare document shape and counts without switching tools constantly
That shortens the risky part of the workflow: the part where you are deciding whether the import actually did what you intended.
Summary
Importing JSON into MongoDB is safe when you are explicit about three things: file shape, type fidelity, and destination behavior.
Check whether the file is a JSON array. Use --jsonArray when needed. Treat _id values as a deliberate decision, not an afterthought. Be careful with dates and ObjectIds. Verify the result with counts, sampling, and type checks before you trust the collection.
# something missing or wrong? tell us · or open a PR